Bash Scripting Tutorial
Please read and write these tutorial scripts yourself to familiarize
yourself with the syntax and common commands in bash scripting. The line
numbers are included only for reference in the tutorial, they are not
used in the scripts themselves.
The first script we will write is the iconic Hello World script, this
will show how to create a variable and print text to the console.
However before beginning your script first type the following command
into your terminal: which bash
This will print a line something like "/usr/local/bin/bash" to your
console which we may need in your script. The full script we will be
writing looks like this:
- #!/bin/bash
- #declare STRING variable
- STRING="Hello World"
- #print variable on a screen
- echo $STRING
We will first run this script and then look at what each line is
doing. Create a file called "hello_world.sh" using your favorite text
editor and put the above script into the document without the line numbers. Then
save the file and use the command "chmod +x hello_world.sh" in the
directory you saved the file in, and then type "./hello_world.sh" to
execute our script. If the script does not run then replace the first
line with the file path that was returned by your "which bash" command.
If you still encounter problems, please speak to a TA during the next
available lab hours, do not wait until the project is due to try to fix
any problems you encounter. It is most beneficial to rewrite this code
yourself, but a copy is available for download here.
- Line 1 line of any script we will write will be the location of
the interpreter for our script, in this case, the location returned by
our "which bash" command. When we execute our script this location is
used to find the program that will read our script called an interpreter.
- Lines 2 and 4 are comments designated by the # symbol
- Line 3 is the declaration of our variable, keep in mind we could just
have easily named this variable HELLO or GOODBYE and that there is no
type declaration as there would be in C or Java indicating what type of
variable we are creating. We simply choose a name for our variable and
assign it a value.
- Line 5 uses the echo command which is simply a shell command that can
be used at any time in the shell. Try this now by typing "echo stuff"
into your terminal to see the results. The $ symbol prior to the STRING
variable is a symbol used to reference our variable and if we had left
off this symbol the output of our program would have been "STRING"
instead of "Hello World".
if_else.sh
- #!/bin/bash
- directory="./Scripting"
- #if statement to check if directory exists
- if [ -d $directory ]; then
- echo "Directory exists"
- else
- echo "Directory does not exist"
- fi
Again it is best to rewrite this code yourself but a copy is
available for download here. See the previous
example for how to run this script.
- Line 1 contains our interpreter file path
- Line 2 contains a variable declaration to a fictional directory
- Line 4 begins our if statement with a conditional in brackets
followed by a semi-colon and the "then" keyword which must follow if
statements. It is important to note that the brackets must not be
touching the reference to our variable. For a listing of some common
conditional statements please see this
page.
- Line 5 and 7 are essentially print statements to the console
- Line 6 contains the else statement, nothing special about it
- Line 8 contains the "fi" keyword which closes the innermost un-closed
if statement, all if statements must be closed with this keyword.
pipes.sh
- #!/bin/bash
- echo "Retrieving data about" $USER
- who | grep $USER
This short and simple bash script demonstrates the use of pipes and
the environment variable $USER in order to retrieve information about the
current user using the who and grep commands. For more information about
these commands type "man who" or "man grep" into your terminal. To get a
better idea of what they return, also try typing the command who itself
into your terminal. This illustrates how you can use commands such as cd
or who in both the terminal and bash script for the same effect. To get
a list of all environment variables type printenv into your terminal. A
copy of this script is available here.
- Line 2 uses the familiar echo command to print a message to the
console. It also uses the environment variable $USER which is a variable
stored in the shell's environment variables. See the above description
for a listing of all environment variables available. This particular
variable corresponds to the username of the currently active user.
- Line 3 contains the who and grep commands which you can obtain more
information about from the "man" command. The pipe symbol "|" forwards
the output of the preceding command as the input of the following
command. Pipes can be chained like so: ls | grep a | echo.
passing_arguments.sh
- #!/bin/bash
- echo $1 $2 $3
A copy of this script is available here. Run this script by typing
"./passing_arguments.sh Why Hello There!" into your terminal.
- Line 2 contains the $ refernce symbol from our introduction to
variables but with three numbers. These numbers (and more if necessary)
contain the arguments passed to the script in order as you can see from
running the code.
file_io.sh
- #!/bin/bash
- echo Hello there people! > outfile.txt
- cat < outfile.txt
A copy of this script is available here.
- Line 2 contains the ">" symbol which redirects all output from a
command to the file followed by the symbol.
- Line 3 contains the "<" symbol which provides input to the command
from the file followed by the symbol.
mail_hello.sh
- #!/bin/bash
- echo "Hello $USER!!" > tmp-message
- echo >> tmp-message
- echo "Today is" `date` >> tmp-message
- echo >> tmp-message
- echo "Sincerely," >> tmp-message
- echo " Myself" >> tmp-message
- /usr/bin/mailx -s "mail-hello" $USER < tmp-message
- echo "Message sent."
This script will also be discussed in lecture and is included in the
class slides.
- Lines 3 through 7 use a new operator ">>". This operator appends
to a file rather than overwriting the data already there.
- Line 8 includes the mailx command which also makes use of its -s
command line option to supply a subject for the email as the following
arugment, in this case: "mail-hello", it is then followed by the user to
deliver to, in this case, yourself, and then the file previously written
to is given as input for the rest of the message.
loops.sh
- #!/bin/bash
- # for loop
- for f in $( ls /var/ ); do
- echo $f
- done
-
- COUNT=6
- # while loop
- while [ $COUNT -gt 0 ]; do
- echo Count: $COUNT
- let COUNT=COUNT-1
- done
This script can be found here.
- Line 3 contains a for loop declaration where a variable f is
created that is filled in with each item in the array returned by ls
/var/ on each iteration of the for loop.
- Line 4 prints the name of the file name currently stored in f on each
iteration of the for loop.
- Line 5 has the done keyword signaling the end of the body of the for
loop, this must always be included as if it were a closing brace for a
for loop in the C programming language.
- Line 9 contains a while loop declaration where the count variable is
used with the -gt (greater than) option to compare it to 0.
- Line 11 uses the new let keyword to perform arithmetic on the count
variable.
- Line 12 contains the done keyword which works as described above for
the for loop.
string_manipulation.sh
- #!/bin/bash
- foo="Hello"
- foo="$foo World"
- echo $foo
- a="hello"
- b="world"
- c=$a$b
- echo $c
- echo ${#foo}
This script is fairly self-explanatory. It shows two fairly similar ways
to concatenate strings, one is no better than the other and it is up to
personal preference which you use. The last line shows how to get the
number of characters in a string.
environment_variables.sh
- #!/bin/bash
- echo $HOME
- echo $PATH
- echo $USER
This script is a simple one, it illustates the use of "environment
variables". You can see all the environment variables currently
available by using the command printenv. These are variables that are
persistent throughout the terminal shell you are using and are available
to programs and scripts run in the shell.
example.sh
- #!/bin/bash
- COUNT=10
- if /usr/xpg4/bin/egrep -q [0-9] testdoc.txt ; then
- let COUNT=COUNT+5
- fi
- echo $COUNT
This script is a simple example of what part of your script for the
project might look like. This will check if the document contains a line
with numbers and then will increment the count if it does
References:
http://bash.deta.in/abs-guide.pdf
http://www.faqs.org/docs/bashman/bashref_68.html
http://linuxconfig.org/bash-scripting-tutorial#h12-loops