1. Getting started
Identify which bash is being used$ which bash
$ bash --version
Create a folder "tutorial" for our tutorial scripts. Enter all the tutorial scripts in this folder.
$ mkdir tutorial
$ cd tutorial
2. Creating a script
This is nothing more than creating a text file loaded with some bash commands. The script will need to have permission to execute, similar to a program. The script can be created using a text editor (e.g. vi, emacs, nano, gedit, kwrite, notepad) or redirect from the shell. Usually, the script files have extension .sh to indicate its a script.Create your first shell with redirect and name it as hello.sh and run (execute) it.
$ date > hello.sh
$ cat hello.sh
$ ls -l hello.sh
$ chmod +x hello.sh
$ ls -l hello.sh
$ ./hello.sh
3. Comments, printout and local strings
- The first line of a shell script is usually with a #! to identify the type of shell to be used with the script.
- The hash or # at beginning of a line shows a comment and commands are not executed.
- The variable name followed by equals or = is to declare a value for a variable. No spaces are allowed before and after the equals sign. Its a practice to have variables in UPPERCASE.
- To printout text and variables, the echo command is used.
Example 1: Print a text string
Edit hello.sh with following;#!/bin/bash
# Tutorial for variables
NAME="Hello world"
echo $STRING
Notice that the declaration of variables do not use the $. Only when we need to access the value in a variables, then we use the $ sign. Run hello.sh
Example 2: Print variable from Linux commands
Append to hello.sh with following;S1=$(date +%Y%m%d)Run hello.sh
echo $S1
4. Builtin variables
There are a number of environment variables and system variables that can be of use when doing scripting. These are also known as builtin variables. Useful commands to know are (printenv, env, set).Append to hello.sh with following;
echo $HOME
echo $BASH_VERSION
Run hello.sh
List of Builtin variables
- BASH_VERSION
- HOSTNAME
- CDPATH
- HISTFILE
- HISTSIZE
- HOME
- IFS
- LANG
- PATH
- PS1
- PS2
- TMOUT
- TERM
- SHELL
- DISPLAY
- EDITOR
- USER
- PWD
- .
Environment variables are shaded and without shading are the system variables.
5. Backup a folder
Create the following script backup_tutorial.sh and execute it.
#!/bin/bash
# Tutorial to backup HOME folder
S1=$(date +%Y%m%d)
BACKUPFILE="$HOME/tutorial-$S1.tgz"
tar czf "$BACKUPFILE" $HOME/tutorial
ls -l $BACKUPFILE
6. Separate variable names and back slash
The brace quotes { } are used to enclose a variable name. The back slash is used to display escape characters and otherwise non printable characters.
Create the following script var_basic.sh and execute it.
#!/bin/bash
# Tutorial on braces
CITY=London
COUNTRY=UK
echo "${CITY},${COUNTRY}"
echo "\"${CITY}\" is in ${COUNTRY}"
7. Linux command in scripts
The back quotes will execute linux commands and return a value that can be saved to a variable.
Create the following script var_command.sh and execute it.
#!/bin/bash
# Tutorial on back quotes
S1=`uname -a`
echo $S1
Alternatively, the Linux command output can be directly displayed or saved to a file.
Append script var_command.sh and execute it.
date "+T"
echo "Currently the Linux have following socket connections"
ss
8. Function basics
Functions are useful to separate group of commands and it allows use of a local variable to that function that does not affect rest of variables.
Create the following script var_function.sh and execute it.
#!/bin/bash
# Tutorial on function and local variables
NAME="Linux"
function display_name {
local NAME=`uname -a`
echo $NAME
}
function display_date {
local NAME=`date "+%D"`
echo $NAME
}
function display_time {
local NAME=`date "+%T"`
echo $NAME
}
echo $NAME
display_name
echo $NAME
display_date
echo -n "$NAME "
display_time
In above example, it also shows the echo with -n to continue next print at the same line.
9. Script arguments
When running a script, users can pass one or more arguments. In the script this is stored as the variable $1, $2, $3, .... or in an array as $@. The $# indicates total number of arguments.
Create the following script var_args.sh and execute it as var_args apple banana grapes
#!/bin/bash
# Tutorial on script arguments
echo "Arguments are "
echo $1
echo $2
echo $3
echo "All are stored as $@"
echo "Total number of arguments are $#"
10. Accepting user input
The command read will prompt for the user to enter test and press Enter.
Create the following script var_user_input.sh and execute it.
#!/bin/bash
# Tutorial on user input
echo "Enter a colour:"
read S1
echo "Enter a country name:"
read S2
echo "$S2 is feeling $S1"
11. Simple if/else decision
The if/else command is space sensitive. It starts with "if" and ends with "fi". The condition is within a square bracket [ ] and can be in any one of these test
- numerical comparison ( -lt, -gt, -le, -ge, -eq, -ne)
- string comparison (=, !=, <, > , -n S1, -z S1)
- file test
- -b filename file is a block special file
- -c filename file is a special character file
- -d directoryname directory exist
- -e filename file exist
- -f filename regular file exist and not a directory
- -G filename file exists and is owned by effective group ID.
- -g filename file exists and is set-group-id.
- -k filename file is sticky bit
- -L filename file is a Symbolic link
- -O filename file exists and is owned by the effective user id.
- -r filename file is a readable
- -S filename file is socket
- -s filename file is nonzero size
- -u filename file set-ser-id bit is set
- -w filename file is writable
- -x filename file is executable
Example 1: File test
Create the following script var_ifelse.sh and execute it.
#!/bin/bash
# Tutorial if/else
DIR="/var/log"
if [ -d $DIR ]then
echo "Directory $DIR exist"
else
echo "Directory $DIR does not exist"
fi
Example 2: numerical test
Create the following script var_ifcondition1.sh and execute it.
#!/bin/bash
# Tutorial if/else
echo "[1]Disk usage, [2]Sockets in use, [9]Help. Choice:"
read CHOICE
if [ $CHOICE -eq 1 ]; then
df
fi
if [ $CHOICE -eq 2 ]; then
ss
fi
if [ $CHOICE -ge 3 ]; then
echo "Type 1 or 2 and press enter"
fi
Example 3: String test
Create the following script var_ifcondition1.sh and execute it.
#!/bin/bash
# Tu torial if/else
S1=`date "+%a"`
echo "Guess a day between Mon and Sun:"
read GUESS
if [ $GUESS = $S1 ]; then
echo "You read my mind"
else
echo "Guess again"
fi
[Tutorial Main]