The Linux Shell and BASH Scripting
The Linux Shell and BASH Scripting
$ more example_script
#!/bin/bash
/usr/bin/nmbd -D
/usr/bin/smbd -D
The Linux Shell
The Saigon CTT
• /etc/profile
• ~/.bash_profile,
~/.bash_login,
~/.profile, ..
Default environment variables : PS1, PS2,
HOME, LOGNAME, SHELL, PATH,
PAGER, LPDEST, PWD, DISPLAY,
MAIL, ..
Alt+Fn
Ctrl+Z, Ctrl+C, *, ?, …
Redirecting Input and Output
The Saigon CTT
Pipe (|)
#ls –l *.JPG | tee file_name
#ls –al /root | grep error >error_file
Do Not use :
#ls –al | xarg grep README
Background jobs
The Saigon CTT
Job
#ls –l *.JPG | tee file_name
#ls –al /root | grep error >error_file
Backround jobs :
- Append with (&)
or
- Ctrl+Z and #bg %job_id
Variables
The Saigon CTT
# VAR1=“This is a String1”
# VAR2=“$VAR1xyz”
# VAR3=“${VAR1}xyz”
# VAR4=‘${VAR1}xyz’
# echo $VAR1; echo $VAR2; echo $VAR3
# echo $VAR4
This is a String1
Nothing # default
This is a String1xyz
Passing Info to Sript
The Saigon CTT
Syntax :
for <variable> in <list>
do
#list of commands to do
done
The for loop Example
The Saigon CTT
#!/bin/bash
for file in $(ls *.txt)
do
newname=“$(basename $file .txt).html”
mv $file $newname
done
The while and until loop
The Saigon CTT
Syntax :
while <condition>
do
#list of commands to do
done
until <condition>
do
#list of commands to do
done
The while loop Example
count=0
The Saigon CTT
Case test:
case expression in
pattern1 )
action
;;
pattern2 )
action
;;
…
esac
case test Example
while [ $1 ]
The Saigon CTT
do
echo –n “$1 hits the “
case $1 in
a?c | ab? )
echo “first case.” ;;
abcde )
echo “second case.” ;;
abc123 )
echo “third case.” ;;
* )
echo “fallout case.” ;;
esac
shift
done
Input
The Saigon CTT
Commands :
read
select
Input - read
The Saigon CTT
Syntax :
#!/bin/bash
Syntax :
do
done
Functions
The Saigon CTT
Syntax:
function function_name
{
}
Or
function_name ()
{
}
Functions
The Saigon CTT
Arithmetic Expression :
Arrays : var[subscript]
More thrilling Examples
for file in $(ls file*)
do
mv $file ${file%html}txt
done
Summary
The Saigon CTT