Mac OSX

How to create & run shell script on macOS

Running a shell script on macOS is similar to using a unix operating system. A shell script can help you perform command line operations on your mac with quite an ease. Furthermore, you can bind shell script with keyboard shortcuts to run every time you need to create repeated commands.

Create shell script

Your first shell script needs to be simple. Open TextEdit on macOS and click New Document where you want to save the shell script. Write the below code:

#!/bin/bash
echo "Talk of Web - Educating Masses"

Save the file with name talkofweb.sh and remember the path of the file. If you can’t save the file using TextEdit with .sh extension then better use a third party code editor like Sublime Text or simply create .sh file with nano command on terminal.

Run shell script using terminal

Open terminal on macOS and navigate to the directory using cd command where you’ve placed talkofweb.sh and run the following command:

  • sh talkofweb.sh

The output of the command is simple. The terminal window will show you something similar to this:

Run shell script on macOS
Run shell script on macOS

In case shell script gives you permission error than you need to give appropriate permissions. Use the following command:

  • chmod +x talkofweb.sh

The above command once executed for the require script file will give it execution permissions on your mac. A common error if you don’t give the required permissions is Permission denied.

Create Z Shell script instead of Bash

Since days of macOS Catalina, Apple is using Z shell instead of Bash. Therefore, bash_profile no more exists, as a result you can use the following code to create same shell script as done in the first step:

#!/bin/zsh
echo "Talk of Web - Educating Masses"

The method to execute a zsh shell script is same as using sh command with the name of the .sh file.

Shell script example on macOS

Let’s create a basic script which may list the contents of a directory (Documents) into a text file. Use a text editor of your choice and save it with the following code:

#!/bin/zsh
cd ~/Documents
ls > ~/Documents/listings/documents_listing.txt

Name the file with the command listings.sh and run it.

  • sh listings.sh

You’ll notice that a documents_listing.txt is created in the given location of the script with details of all the files stored inside Documents folder on your mac.

Shell script example on macOS
Storing documents files in txt file using Shell script

Conclusion

You can use shell script on macOS for a number of reasons, such as using similar commands repeatedly or performing operations on folders. Shell script option saves your time as well as effort required to type commands in terminal every time you want to do a repeated task on your laptop. You can use the same shell script on Linux or Unix operating system.