How-to: Run a shell script

A shell script is an ASCII text file containing one or more commands.

#!/bin/bash
# My example bash script
echo "Hello World"

The first line contains a shebang #! followed by the path to the shell, in this case bash - this acts as an interpreter directive and ensures that the script is executed under the correct shell.

The # character indicates a comment, so the shebang line is ignored by bash when running the script.

The same thing with the zsh shell:

#!/bin/zsh
# My example shell script
echo "Hello World"

Next you need to make the script executable with chmod

$ chmod u+x my_shell_script.sh

You can now run the script by prefixing it with ./

$ ./my_shell_script.sh

If you get an error like "#!/bin/bash: No such file or directory", that is typically an indication that the File encoding or line endings are wrong, use an editor like VI or BB Edit (shows line encodings at the bottom of the edit window) the script file should be Unicode (UTF-8) and Unix (LF) line endings

Double click on a script to run

In macOS, there is a default file association between .command files and the terminal, so if you rename a shell script from a more conventional my_shell_script.sh to my_shell_script.command then you will be able to just double click the icon in the Mac finder to execute the script.

Making a script available everywhere

If you will be writing a few shell scripts then it’s worth creating a folder, perhaps called "scripts" and adding that to the system path:

$ mkdir -p $HOME/scripts
$ export PATH="$PATH:~/scripts"

Next edit your .bash_profile or .zshrc file to include export PATH="$PATH:~/scripts" that will keep the "scripts" folder in your path every time you log in.

With a script saved in that folder, you can now run it no matter what your current working directory is, with just:

$ my_shell_script.sh

Enable drag and drop of files into a script

AppleScripts are created using "Utilities / Script Editor" and then saved as type= application.

The example below can be activated by dragging and dropping a file onto it.

This will execute a Unix command or script passing the filename, you can also drop multiple files at once and it will execute for each file in turn:

on open filelist
  repeat with i in filelist
    set posixPath to quoted form of POSIX path of i
    do shell script "some_shell_script.sh " & posixPath
  end repeat
end open

Related macOS commands

exec - Execute a command.
How-to: Run a script at startup/login
macOS How To


 
Copyright © 1999-2025 windevcluster.com
Some rights reserved