Run a bash shell script

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

# 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.

Next you need to make the script executable with chmod

$ chmod u+x

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

$ ./

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:


Passing parameters to a shell script:

$ cat
echo 'Welcome' $0 'says' $1 $2

$ chmod a+x
$ Hello world
Welcome says Hello world

Running scripts from the system path

A shell script is a text file containing shell commands. When such a file is used as the first non-option argument when invoking Bash, and neither the `-c' nor `-s' option is supplied, Bash reads and executes commands from the file, then exits. This mode of operation creates a non-interactive shell.


In other words, executing

filename arguments

is equivalent to executing

bash filename arguments


Most versions of Unix make this a part of the operating system's command execution mechanism. If the first line of a script begins with the two characters `#!', the remainder of the line specifies an interpreter for the program. Thus, you can specify Bash, awk, Perl, or some other interpreter and write the rest of the script file in that language.



When Bash runs a shell script, it sets the special parameter $0 to the name of the file, rather than the name of the shell, and the positional parameters are set to the remaining arguments, if any are given. If no additional arguments are supplied, the positional parameters are unset.

Adding the following two set options to your scripts can be useful to catch undefined variables ("") and to exit if a command fails:

set -o nounset
set -o errexit


This usually means the file has been edited and has Windows <CR-LF> instead of unix <LF> line endings


BASH Syntax
set - Manipulate shell variables and functions
Windows equivalent command: CMD - Start a new CMD shell

© Copyright 1999-2015
Some rights reserved