Run a bash shell script

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

#!/bin/bash
# My example bash script (the comment line above ensures this will run under bash)
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 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"

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

With the script saved in the folder, you can now run it with just:

$ my_shell_script.sh

Errors:

/bin/bash^M: bad interpreter: no such file or directory
This usually means the file has been edited and has Windows <CR-LF> instead of unix <LF> line endings.

Related:

OS X Syntax



Back to the Top

© Copyright SS64.com 1999-2010
Some rights reserved