Useful scripts for macOS

Getting Started

You might find these articles useful

One of the advantages with scripts is the fact that you can easily automate many tasks. Here is an article that walks you through that process.

If you come across a situation where you want to perform a set of tasks on multiple computers then scripts come in very handy.

I will be providing the Shell Script version of the task. Feel free to make changes to the scripts as required. I will try to provide an AppleScript version of the tasks a little later.

This is not the only way to implement the scripts. There may be multiple approaches towards achieving the same result. You will have to explore and examine the correct approach.

This is not a comprehensive list. The scripts should give you some ideas and act as a useful reference when you are creating your own scripts.

I have tested these scripts on macOS Catalina 10.15

Download

You can download all the scripts from here.

Script CategoryPage Number
Settings and Accounts1
Security2
Data3
Information Collection4
File System5

Disclaimer

The Software Is Provided “As Is”, Without Warranty Of Any Kind, Express Or Implied, Including But Not Limited To The Warranties Of Merchantability, Fitness For A Particular Purpose And Noninfringement. In No Event Shall The Authors Or Copyright Holders Be Liable For Any Claim, Damages Or Other Liability, Whether In An Action Of Contract, Tort Or Otherwise, Arising From, Out Of Or In Connection With The Software Or The Use Or Other Dealings In The Software.


WARNING

Please try these scripts on a test computer. Some of the scripts do make changes to the system. Always test before using these scripts.

Advertisement

Using Swift Package Manager

About Swift Package Manager

The Swift Package Manager is the tool used to build Applications and Libraries. it streamlines the process of managing multiple Modules & Packages. Before we go ahead and learn to use Swift Package Manager we need to get familiar with some basic terminology.

Modules

Modules are used to specify a namespace and used to control access to that particular piece of code. Everything in Swift is organised as a module. An entire app can fit into a module or an app can be made using multiple modules. The fact that we can build modules using other modules means that reusing code becomes a lot easier. So, when we make an iOS App with Xcode and Swift. The entire app is considered a single module.

Targets

Targets are the end product that we want to make. So an app for iOS is a separate target. A library is a target. An app for macOS is a separate target. You can have many targets. Some can be for testing purposes only.

Packages

Packages group the necessary source files together. A package can contain more than one target. Normally one would create a package for a family of products. For example: you want to make a photo editing app that runs on macOS & iOS. You would create one package for it. That package would have 2 targets: an iOS App & a macOS App.

Products

This is a categorisation of your packages. There are 2 types of products. Executables or Libraries. A library contains the module which can be reused elsewhere. Executables are application that run & may make use of other modules.

Dependencies

Dependencies are the modules or the pieces of code that are required to make the different targets within the package. These are normally provided as URLs.

End Products

*NOTE: Before you get started you must be familiar with Setting up Swift on Linux. If you haven’t done that then please go through the updated article: UPDATE: Swift on Linux. This also makes use of Swift Package Manager.

Example

So let us get started with an example. We are going to learn how to create:

  • a library package called ErrorTypes
  • a library package, called MathOperations, that uses the ErrorTypes library package
  • an executable package called Calc that makes use of the MathOperations package.

We will see how to create all three elements. Also I have uploaded the ErrorTypes & MathOperations packages to the http://www.github.com repository to demonstrate the use of dependencies. You can also create your own local git repositories if you wish.

To illustrate the folder hierarchy: I have created a folder called “Developer” in my Ubuntu linux home folder. Within that I have created a folder called “SPMDEMO“. All the paths that I will be using will be with reference to these folders. You should see a structure like this:

/home/admin/Developer/SPMDEMO/ErrorTypes
/home/admin/Developer/SPMDEMO/MathOperations
/home/admin/Developer/SPMDEMO/Calc

You are free to follow this exercise using your own folder locations. Just modify the paths accordingly.

swift package init
swift package init --type executable
swift build

If you need help with the commands run:

swift package --help
swift --help

Creating a Package

  1. First let us start off by creating the ErrorTypes package.
    mkdir ErrorTypes
  2. Navigate to the folder and create the package:
  3. cd ErrorTypes
    swift package init
    

    By default init will create a library package type.

  4. Navigate to the folder containing the source files:
    cd ./Sources/ErrorTypes/
  5. Open the ErrorTypes.swift file and write the following code
    public enum ErrorCodes : Error
    {
         case FileNotFound(String)
         case DivideByZero(String)
         case UnknownError(String)
    }
    
    public struct MathConstants
    {
         static let pi : Float = 3.14159
         static let e  : Float = 2.68791
    }
    

    Feel free to add some code of your own. The above is just an example.

  6. Run the command to build to make sure that there aren’t any issues. You shouldn’t have any as there are no dependencies of any kind. Its a simple straightforward piece of code.
    swift build
  7. If everything is fine check your code into a git repository. This can be local or on the web. Remember that we will need the URL to this repository.
  8. Navigate back to the SPMDEMO folder.
    cd ~/Developer/SPMDEMO/
  9. Create a folder called MathOperations.
    mkdir MathOperations
  10. Navigate to the newly created folder and run the command to create a library package.
    cd MathOperations
    swift package init
    
  11. Navigate to the sources folder:
    cd ./Sources/MathOperations/
  12. Open the MathOperations.swift file and write the following code.
    import ErrorTypes
    
    public struct MathOperations
    {
         public static func add(Number num1 : Int, with num2 : Int) -> Int
         {
              return num1 + num2
         }
    
         public static func mult(Number num1 : Int, with num2 : Int) -> Int
         {
              return num1 * num2
         }
    
         public static func div(Number num1 : Int, by num2 : Int) throws -> Int
         {
              guard num2 > 0
              else
              {
              throw ErrorCodes.DivideByZero("You are dividing by zero. The second argument is incorrect.")
              }
    
              return num1 / num2
         }
    
         public static func sub(_ num1 : Int, from num2 : Int) -> Int
         {
              return num2 - num1
         }
    }
    
  13. Before we build we need to modify the Packages.swift file to indicate there is a dependency.
    Notice that in the MathOperations.swift file we are importing a module called ErrorTypes. We just created it. But just because we created it doesn’t mean it will be added automatically. We need to pull that module into our own

    Also notice that I have provided access specifiers “public” everywhere. This ensures that the code written in one module is accessible in the other.

    Navigate to the MathOperations parent folder.

    cd ~/Developer/SPMDEMO/MathOperations/
  14. Open the Packages.swift file and make the changes as shown below:
    // swift-tools-version:4.0
    // The swift-tools-version declares the minimum version of Swift required to build this package.
    
    import PackageDescription
    
    let package = Package(name: "MathOperations",
         products: [
              // Products define the executables and libraries produced by a package, and make them visible to other packages.
              .library(name: "MathOperations", targets: ["MathOperations"]),
         ],
    
         dependencies: [
              // Dependencies declare other packages that this package depends on.
              .package(url:"https://github.com/AmaranthineTech/ErrorTypes.git", from:"1.0.0"),
         ],
    
         targets: [
              // Targets are the basic building blocks of a package. A target can define a module or a test suite.
              // Targets can depend on other targets in this package, and on products in packages which this package depends on.
              .target(name: "MathOperations", dependencies: ["ErrorTypes"]),
              .testTarget(name: "MathOperationsTests", dependencies:   ["MathOperations"]),]
    )
    
  15. Once these changes are made save the file and run the command
    swift build

    If you typed everything correctly then you should see the source code for the ErrorTypes module being pulled in and the build being successful.Here are some common mistakes:
    – Forgetting to write the import ErrorTypes statement
    – Error in the URL
    – The from tag not matching the tag in the repository
    – Access specifiers are incorrect or missing
    – Not mentioning the dependencies in the target

  16. Just like with the ErrorTypes module create a git repository for the MathOperations module.
  17. Now let us make the Calc executable that will use the MathOperations library. First navigate back to the SPMDEMO folder and create a folder called Calc.
    cd ~/Developer/SPMDEMO/
    mkdir Calc
    
  18. This time we are going to create an executable package. Run the command:
    swift package init --type executable

    This also creates a similar folder structure as in the case of the library.

  19. Navigate to the folder containing the main.swift file.
    cd ./Sources/Calc/
  20. Modify the main.swift file as shown below:
    import MathOperations
    
    //testing addition
    var result : Int = MathOperations.add(Number: 33, with: 29)
    print("Result of adding 33 with 29 is: \(result)")
    
    //testing multiplication
    result = MathOperations.mult(Number: 33, with: 29)
    print("Result of multiplying 33 with 29 is: \(result)")
    
    //testing division
    do
    {
         result = try MathOperations.div(Number: 33, by: 0)
         print("Result of dividing 33 by 29 is: \(result)")
    }
    catch let error
    {
         print("ERROR: \(error)")
    }
    
    //testing subtraction
    result = MathOperations.sub(3, from: 29)print("Result of subtracting 3 from 29 is: \(result)")
    
  21. Navigate back to the main Calc folder.
    cd ~/Developer/SPMDEMO/Calc/
  22. Modify the Packages.swift file as shown below:
    // swift-tools-version:4.0
    // The swift-tools-version declares the minimum version of Swift required to build this package.
    
    import PackageDescription
    
    let package = Package(name: "Calc",
    dependencies: [
         // Dependencies declare other packages that this package depends on.
         .package(url: "https://github.com/AmaranthineTech/MathOperations.git", from: "1.0.1"),
    ],
    targets: [
         // Targets are the basic building blocks of a package. A target can define a module or a test suite.
         // Targets can depend on other targets in this package, and on products in packages which this package depends on.
         .target(name: "Calc", dependencies: ["MathOperations"]),
    ]
    )
    
  23. Save the file and run the build command:
    swift build
  24. Like before you should see both the MathOperationsErrorType module being pulled in. We are ready to run the executable. Navigate to the debug folder which contains the executable. Make sure you are in the main Calc folder when you run this command.
    cd ./build/debug/
  25. You should see an executable file called Calc. Run it.
    ./Calc
  26. If everything went okay then you should see the output on the console.

As you can see it is pretty straightforward to develop Applications written in Swift on Linux.

Adding System Modules

In the previous example we saw how to import our own custom made modules. However, there are some modules provided by the system which offers functionality we may wish to use. For example if we wanted to use the random number generator in our application we would need to use the random() method. This is in the glib module.

  1. Quickly create a package called SystemLibs. This is an executable.
  2. Write the following code in the main.swift.
    #if os(Linux)
    import Glibc
    #else
    import Darwin.C
    #endif
    extension Int
    {
         func toString() -> String
         {
              return "\(self)"
         }
    }
    
    var luckyNumber : Int = Int(random())
    
    var luckyNumberStr : String = luckyNumber.toString()
    
    print("The lucky number is \(luckyNumberStr)")
    
  3. Build the code and run the executable.

Adding system modules is direct and simple. The glibc module contains aspects of the standard library. The condition check is to make sure that we are importing the correct module based on the system that we are developing the application on.

Handling Sub-dependencies

As we saw in the earlier example, sub dependencies are handled automatically. So when our Calc application marked the MathOperations module as a dependency it was pulled during the build. However, the MathOperations module itself marked ErrorTypes module as a dependency. We did not have to modify the Packages.swift file belonging to Calc to indicate that ErrorTypes module also needs to be pulled. This was handled automatically by Swift Package Manager.

Conclusion

In this article we have seen:

  • How to create a library package
  • How to create a library package that depends on another library package
  • How to create an executable that depends on a library package
  • How to import the system Glibc module into our executables.

The Swift Package Manager simplifies many aspects of the development process for us. Many of the things we have discussed also work on macOS. Going forward reusing code and planning for the same should be done keeping Swift Package Manager in mind.

UPDATE: Swift on Linux

This article is an UPDATE for Writing Swift Programs on Linux

This article uses Command Line Interface(CLI) to write Swift Programs. If you are new to CLI then you should read the following articles: Terminal Commands for OS X – BasicTerminal Commands for OS X – Part 2.

This article has been written using Ubuntu version 16.04 LTS

For the best part the process is still the same.

  1. Download the Swift tools for Linux from: Swift Download Page
  2. Untar the downloaded files
  3. Copy them to a folder of your choice. I have created a folder called “Developer” in my home folder. So I copied the untarred contents there. This is important because we will be needing the location later.
  4. Switch to Terminal on your Ubuntu System.
  5. First we will install clang. Run the command
    sudo apt-get install clang
  6. Next we will make sure we set the PATH to the path where we copied the Swift tools. For example if the Untarred swift folder is called “swift-4.0-DEVELOPMENT-SNAPSHOT-2017-12-04-a-ubuntu16.04/usr/bin:”${PATH}” and it is in the Developer folder I created earlier then the command would be:
    export PATH=/home/admin/Developer/swift-4.0-DEVELOPMENT-SNAPSHOT-2017-12-04-a-ubuntu16.04/

    The folder name will vary from system to system. The path above is just an example.

  7. Let us check to make sure that everything installed okay. We can do this with 2 commands:
    which swift

    This should show you the path to the folder.
    or

    swift --version

    This should print out the swift version.

  8. Next let us test the REPL. Run the command:
    swift

    This will result in a prompt that looks like:

    Welcome to Swift version 4.0.3-dev (2dedb62a0b, Clang ab7472e733, Swift 64ab6903b2). Type :help for assistance.
     1>
    
  9. Type some of the commands mentioned below:
    12 * 8
    let hello = "Welcome to Swift in Linux"
    print(hello)
    
  10. Now that we know that the REPL is working well, let us move on to the next stage. Let us quit from the REPL:
    :q

Creating Single File Projects

  1. Next let us use Swift Package Manager to create a single file project. I will be creating the project in the Developer folder. So I will navigate to it:cd ~/Developer/
  2. Create a folder of your choice, lets call it Hello World:
    HelloWorld
  3. Enter the folder:
    cd HelloWorld
  4. Create a manifest file for the Package with the command:
    swift package init

    This will create some content for you. The structure should look as shown below.Screen Shot 2018-03-27 at 10.24.02 AM

  5. If we run the command to build it will simply create a module for us. To do that type and run:
    swift build
  6. But we would like to create an executable application. In the sources folder create a file called main.swift. You can use the command:
    touch main.swift

    to quickly create a new swift file.

  7. Open the main.swift file. Write the following code in there:
    let object : HelloWorld = HelloWorld()
    print(object.text)
    print("End of program...!")
    
  8. To create the executable we will first build our code:
    swift build
  9. Now we will run the executable, assuming that you are still in the HelloWorld folder within the sources folder navigate to a hidden build folder. To do that first we will navigate to our main HelloWorld package folder.
    cd ../..
  10. To view all the folders including the hidden folders run the list command:
    ls -la
  11. Navigate to the hidden folder and the debug folder inside it to locate the executable:
    cd .build/debug/
  12. To run the executable:
    ./HelloWorld
  13. If you want to build and directly run & avoid doing steps 9-13 repeatedly the command is:
    swift run

Next we will see how to create multi file projects

Create Multi File Projects

    1. In the previous project go back to the HelloWorld folder within the Sources folder. Create a file called converter.swift:
      touch converter.swift
    2. Write the following code in that file:
      //note the code below is for demonstrating multi file projects & may not necessarily be accurate or correct
      
      //note the code below is for demonstrating multi file projects & may not necessarily be accurate or correct
      func centigrade_to_fahrenheit(temperatureInCentigrade : Float) -> Float
      {
           return ((temperatureInCentigrade*9.0/5.0)+32.0)
      }
      
      func string_to_float(input : String) -> Float
      {
           var number : Float = 0.0;
           var result : Float = 0.0
           var decimalFound : Bool = false
           var numberOfDigitsAfterDecimal : UInt8 = 0
      
           for charac in input
           {
                switch charac
                {
                     case "0":
                          number = 0.0;
                          result = (result * 10.0) + number;
                     case "1":
                          number = 1.0;
                          result = (result * 10.0) + number;
                     case "2":
                          number = 2.0;
                          result = (result * 10.0) + number;
                     case "3":
                          number = 3.0;
                          result = (result * 10.0) + number;
                     case "4":
                          number = 4.0;
                          result = (result * 10.0) + number;
                     case "5":
                          number = 5.0;
                          result = (result * 10.0) + number;
                     case "6":
                          number = 6.0;
                          result = (result * 10.0) + number;
                     case "7":
                          number = 7.0;
                          result = (result * 10.0) + number;
                     case "8":
                          number = 8.0;
                          result = (result * 10.0) + number;
                     case "9":
                          number = 9.0;
                          result = (result * 10.0) + number;
                     default:
                          decimalFound = true
                          break
                }
                if decimalFound
                {
                     numberOfDigitsAfterDecimal += 1
                }
           }
      
           for _ in 0..<numberOfDigitsAfterDecimal-1
           {
                result = result / 10.0
           }
           return result
      }

 

  1. Write the following code in the main.swift file:
    let object : HelloWorld = HelloWorld()
    if CommandLine.arguments.count != 2
    {
            print("USAGE: centigradeToFahrenheit 33.4")
            print("You are missing an argument")
    }
    else
    {
            let temperatureInCentigrade = string_to_float(input: CommandLine.arguments[1]) 
    
            print("\(temperatureInCentigrade) is equal to \(centigrade_to_fahrenheit(temperatureInCentigrade: temperatureInCentigrade))")
    }
    print(object.text)
    print("End....!")
    
  2. Build and run the code. To run it while passing arguments in:
    ./HelloWorld 33.4

So that is how you can build single file & multi file Swift applications on Linux.