Bash Script Tutorial

Knowledge | Unix/Linux Tutorials


Bash Scripting Tutorial

This bash script tutorial assumes no previous knowledge of bash scripting. As you will soon discover in this quick comprehensive bash scripting guide, learning the bash shell scripting is very easy task. However, if you do not find an answer to your questions by reading this bash tutorial or you need extra help, feel to send us an email with the specify question. We will be more than happy to help you with your bash questions there.

Lets begin this bash scripting tutorial with a simple “This is my First Example” script. Let’s start with learning the bash Shell: Unix Shell Programming.

First, we need to find out where is the bash interpreter located. Enter the following commands into your command line:

$ which bash

Output:

/bin/bash

Second, Open up your favorite text editor and create a new file called “My_first_example.sh”. Insert the following lines into it:

#!/bin/bash
#declare string variable
STRING="This is my First Example"
#Print the variable on the screen
echo $STRING

NOTE:Every bash shell script must starts with shebang: “#!” which is not read as a comment. First line is also a place where we must put the interpreter. In this case is: /bin/bash

Third, Make the “My_first_example.sh” executable. Please do the following steps:

$ chmod +x My_first_example.sh

Finally, we are ready to execute our first bash script. Please execute the following command:

./My_first_example.sh


Simple Backup Bash Shell Script

#!/bin/bash
tar -czf my_tarfile.tar.gz /home/<directory1>

Output:

linuxbox:~$./my_backup.sh
tar: Removing leading `/' from member names
linuxbox:~$ls my_tarfile.tar.gz
linuxbox:~$


Variables

In this example we declared a simple bash variable and print it on the screen (stdout) with echo command.

#!/bin/bash
STRING="My First Example"
echo $STRING


Backup and Variables working together

#!/bin/bash
OF=my_backup_$(date +%Y%m%d).tar.gz
tar -czf $OF /home/mydirectory

Output:

linuxbox:~$./my_backup.sh
linuxbox:~$tar: Removing leading `/' from member names
linuxbox:~$ls -l
linuxbox:~$my_backup_20120510.tar.gz


Backup and Variables working together

#!/bin/bash
#Define bash global variable
#This variable is global and can be used anywhere in this bash script
VAR="global variable"
function bash {
#Define bash local variable
#This variable is local to bash function only
local VAR="local variable"
echo $VAR
}
echo $VAR
bash
#Note the bash global variable did not change
#"local" is bash reserved word
echo $VAR

Output:

linuxbox:~$./variable.sh
global variable
local variable
global variable
linuxbox:~$


Passing Arguments to the Bash Script

#!/bin/bash
#Use predefined variables to access passed arguments
#echo arguments to the shell
echo $1 $2 $3 ' -> echo $1 $2 $3'

#We can also store arguments form bash command line in special array
args=("$@")
#echo arguments to the shell
echo ${args[0]} ${args[1]} ${args[2]} ' -> args=("$@"); echo ${args[0]} ${args[1]} ${args[2]}'

#use $@ to print out all arguments at once
echo $@ ' -> echo $@'

#use $# variable to print out
#number of arguments passed to the bash script
echo Number of arguments passed: $# ' -> echo Number of arguments passed: $#'

Output:

linuxbox:~$./arguments2.sh This is an example
This is an  -> echo $1 $2 $3
This is an  -> args=("$@"); echo ${args[0]} echo ${args[1]} ${args[2]}
This is an  -> echo $@
Number of arguments passed: 4  -> echo Number of arguments passed: $#


Execute Shell Commands with Bash

#!/bin/bash
# Use backticks "``" to execute shell command
echo `uname -o`
#executing bash command without backticks
echo uname -o


Reading User Input

#!/bin/bash
echo -e "Hi, please type the word: c"
read word
echo "The word you entered is: $word"
echo -e "Can you please enter two words? "
read word1 word2
echo "Here is your input: $word1 $word2"
echo -e "How do you feel about bash scripting? "
#Read command now stores a reply into the default build-in variable $REPLY
read
echo "You said $REPLY, I'm glad to hear that! "
echo -e "What are your favorite colours ? "
# -a makes read command to read into an array
read -a colours
echo "My favorite colours are also ${colours[0]}, ${colours[1]} and ${colours[2]}:-)"

Output:

linuxbox:~$ ./readme.sh 
Hi, please type the word: Hello
the word you entered is: Hello
Can you please enter two word? 
Hello Customers
Here is your input: Hello Customers
How do you feel about bash scripting? 
Very Good
You said Very Good, I'm glad to hear that! 
What are your favorite colours? 
Blue Orange Red
My favorite colours are also Blue, Orange and Red:-
linuxbox:~$ 


Bash Trap Command

#!/bin/bash
#bash trap command
trap bashtrap INT
#bash clear screen command
clear;
#bash trap function is executed when CTRL-C is pressed:
#bash prints message => Executing bash trap subrutine !
bashtrap()
{
    echo "CTRL+C Detected !...executing bash trap !"
}
# for loop from 1/10 to 10/10
for a in `seq 1 10`; do
    echo "$a/10 to Exit."
    sleep 1;
done
echo "Exit Bash Trap Example!!!"

Output:

linuxbox:~$
1/10 to Exit.
2/10 to Exit.
3/10 to Exit.
CTRL+C Detected !... executing bash trap !
4/10 to Exit.
5/10 to Exit.
6/10 to Exit.
7/10 to Exit.
8/10 to Exit.
CTRL+C Detected !... executing bash trap !
9/10 to Exit.
10/10 to Exit.
Exit Bash Trap Example!!!
linuxbox:~$  


Declare Simple Bash Array

#!/bin/bash
#Declare array with 6 elements
ARRAY=( 'One' 'Two' 'Three' 'Four' 'Five' 'Six' )
# get number of elements in the array
ELEMENTS=${#ARRAY[@]}
#echo each element in array
#for loop
for (( i=0;i<$ELEMENTS;i++));do
      echo ${ARRAY[${i}]}
done

Output:

linuxbox:~$./array.sh
One
Two
Three
Four
Five
Six
linuxbox:~$


Read File Into Bash Array

#!/bin/bash
#Declare array
declare -a ARRAY
# Link file descriptor 10 with stdin
exec 10<&0
let count=0
while read LINE; do
   ARRAY[$count]=$LINE
   ((count++))
done
echo Number of elements: ${#ARRAY[@]}
#echo array's content
echo ${ARRAY[@]}
#restore stdin from file descriptor 10
#and close file descriptor 10
exec 0<&10 10<&-


Bash Script Execution with an Output:

linuxbox:~$
One
Two
Three
Four
Five
Six
linuxbox:~$./arrays1.sh bash1.txt
Number of elements: 6
Bash Scripting Number of Items
linuxbox:~$

Related Articles