About shell scripts in Terminal on Mac
Instead of entering commands and waiting for a response, you can compose shell scripts that run without direct interaction.
A shell script is a text file that contains one or more UNIX commands. You run a shell script to perform commands you might otherwise enter at the command line.
Shell scripts are useful because you can combine many common tasks into one script, saving you time and possible errors when performing similar tasks over and over. You can also automate shell scripts using tools such as launchd
or Apple Remote Desktop.
A shell script begins with a character combination that identifies it as a shell script — specifically the characters # and ! (together called a shebang) followed by a reference to the shell the script should be run with. For example, here’s the first line of a shell script that would be run with sh
:
#!/bin/sh
You should document your shell scripts with comments. To add a comment, start the line with the number sign (#). Every line of a comment needs to begin with the number sign:
#This program returns the
#contents of my Home folder
You can put blank lines in a shell script to help visually distinguish different sections of the script.
You use the chmod
tool to indicate that the text file is executable (that is, its contents can run as a program). See Make a file executable in Terminal on Mac.
For information about how to write shell scripts, see the Shell Scripting Primer on the Apple Developer Connection website.