Linux Scripting
Linux Scripting
php)
Contact us Advertise Here
(/contact-us) (/advertise-here)
Contents [Hide]
Hello World Bash Shell Script (https://linuxconfig.org/bash-scripting-tutorial#h1-hello-world-bash-shell-script)
Simple Backup bash shell script (https://linuxconfig.org/bash-scripting-tutorial#h2-simple-backup-bash-shell-script)
Variables (https://linuxconfig.org/bash-scripting-tutorial#h3-variables)
Global vs. Local variables (https://linuxconfig.org/bash-scripting-tutorial#h3-1-global-vs-local-variables)
Redirections (https://linuxconfig.org/bash-scripting-tutorial#h18-redirections)
STDOUT from bash script to STDERR (https://linuxconfig.org/bash-scripting-tutorial#h18-1-stdout-from-bash-script-to-stderr)
STDERR from bash script to STDOUT (https://linuxconfig.org/bash-scripting-tutorial#h18-2-stderr-from-bash-script-to-stdout)
stdout to screen (https://linuxconfig.org/bash-scripting-tutorial#h18-3-stdout-to-screen)
stdout to file (https://linuxconfig.org/bash-scripting-tutorial#h18-4-stdout-to-file)
stderr to file (https://linuxconfig.org/bash-scripting-tutorial#h18-5-stderr-to-file) Search Articles
stdout to stderr (https://linuxconfig.org/bash-scripting-tutorial#h18-6-stdout-to-stderr)
stderr to stdout (https://linuxconfig.org/bash-scripting-tutorial#h18-7-stderr-to-stdout)
stderr and stdout to file (https://linuxconfig.org/bash-scripting-tutorial#h18-8-stderr-and-stdout-to-file) search ...
Search
Friendly Sites
This bash script tutorial assumes no previous knowledge of bash scripting.As you will soon
Tuxmachines.org (http://tuxmachines.org/)
discover in this quick comprehensive bash scripting guide, learning the bash shell scripting is
(http://linuxconfig- 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 free to ask us on our new Linux Forum
(http://forum.linuxcareer.com). We will be more than happy to help you with your bash questions Latest Configs
there.
Now you are ready to execute your first bash script: logical-volume-snapshots)
I2P - Anonymity for the Masses (/i2p-
./hello_world.sh anonymity-for-the-masses)
Learning Linux Commands: man (/learning-
linux-commands-man)
Linux Command Line & Bash Shell
Shortcuts (/linux-command-line-bash-shell-
shortcuts)
2. Simple Backup bash shell script
How to Install Any Linux Distro on a
Chromebook (/how-to-install-any-linux-
#!/bin/bash distro-on-a-chromebook)
tar -czf myhome_directory.tar.gz /home/linuxconfig Configuration of High-Availability Storage
Server Using GlusterFS (/configuration-of-
high-availability-storage-server-using-
glusterfs)
3. Variables
In this example we declare simple bash variable and print it on the screen ( stdout ) with echo command.
#!/bin/bash
STRING="HELLO WORLD!!!"
echo $STRING
#!/bin/bash
OF=myhome_directory_$(date +%Y%m%d).tar.gz
tar -czf $OF /home/linuxconfig
3.1. Global vs. Local variables
#!/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
#!/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 from 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]}'
#!/bin/bash
# use backticks " ` ` " to execute shell command
echo `uname -o`
# executing bash command without backticks
echo uname -o
#!/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!!!"
8. Arrays
#!/bin/bash
#Declare array with 4 elements
ARRAY=( 'Debian Linux' 'Redhat Linux' Ubuntu Linux )
# get number of elements in the array
ELEMENTS=${#ARRAY[@]}
ARRAY[$count]=$LINE
((count++))
done
Please note the spacing inside the [ and ] brackets! Without the spaces, it won't work!
#!/bin/bash
directory="./BashScripting"
else
-lt <
-gt >
-le <=
-ge >=
-eq ==
-ne !=
#!/bin/bash
# declare integers
NUM1=2
NUM2=2
if [ $NUM1 -eq $NUM2 ]; then
echo "Both Values are equal"
else
echo "Values are NOT equal"
fi
#!/bin/bash
# declare integers
NUM1=2
NUM2=1
if [ $NUM1 -eq $NUM2 ]; then
echo "Both Values are equal"
else
echo "Values are NOT equal"
fi
#!/bin/bash
# declare integers
NUM1=2
NUM2=1
if [ $NUM1 -eq $NUM2 ]; then
echo "Both Values are equal"
elif [ $NUM1 -gt $NUM2 ]; then
echo "NUM1 is greater then NUM2"
else
echo "NUM2 is greater then NUM1"
fi
= equal
!= not equal
< less then
> greater then
-n s1 string s1 is not empty
-z s1 string s1 is empty
#!/bin/bash
#Declare string S1
S1="Bash"
#Declare string S2
S2="Scripting"
if [ $S1 = $S2 ]; then
echo "Both Strings are equal"
else
echo "Strings are NOT equal"
fi
#!/bin/bash
#Declare string S1
S1="Bash"
#Declare string S2
S2="Bash"
if [ $S1 = $S2 ]; then
echo "Both Strings are equal"
else
echo "Strings are NOT equal"
fi
#!/bin/bash
file="./file"
if [ -e $file ]; then
echo "File exists"
else
echo "File does not exists"
fi
Similarly for example we can use while loop to check if file does not exists. This script will sleep until file does exists. Note bash negator "!"
which negates the -e option.
#!/bin/bash
while [ ! -e myfile ]; do
# Sleep until file does exists/is created
sleep 1
done
12. Loops
#!/bin/bash
#!/bin/bash
COUNT=6
# bash while loop
while [ $COUNT -gt 0 ]; do
echo Value of count is: $COUNT
let COUNT=COUNT-1
done
#!/bin/bash
COUNT=0
# bash until loop
until [ $COUNT -gt 5 ]; do
echo Value of count is: $COUNT
let COUNT=COUNT+1
done
12.4. Control bash loop with
Here is a example of while loop controlled by standard input. Until the redirection chain from STDOUT to STDIN to the read command
exists the while loop continues.
#!/bin/bash
# This bash script will locate and replace spaces
# in the filenames
DIR="."
# Controlling a loop with bash read command by redirecting STDOUT as
# a STDIN to while loop
# find will not truncate filenames containing spaces
find $DIR -type f | while read file; do
# using POSIX class [:space:] to find space in the filename
if [[ "$file" = *[[:space:]]* ]]; then
# substitute space with "_" character and consequently rename the file
mv "$file" `echo $file | tr ' ' '_'`
fi;
# end of while loop
done
!/bin/bash
# BASH FUNCTIONS CAN BE DECLARED IN ANY ORDER
function function_B {
echo Function B.
}
function function_A {
echo $1
}
function function_D {
echo Function D.
}
function function_C {
echo $1
}
# FUNCTION CALLS
# Pass parameter to function A
function_A "Function A."
function_B
# Pass parameter to function C
function_C "Function C."
function_D
#!/bin/bash
# bash select
select word in "linux" "bash" "scripting" "tutorial"
do
echo "The word you have selected is: $word"
# Break, otherwise endless loop
break
done
exit 0
15. Case statement conditional
#!/bin/bash
echo "What is your preferred programming / scripting language"
echo "1) bash"
echo "2) perl"
echo "3) phyton"
echo "4) c++"
echo "5) I do not know !"
read case;
#simple case bash structure
# note in this case $case is variable and does not have to
# be named case this is just an example
case $case in
1) echo "You selected bash";;
2) echo "You selected perl";;
3) echo "You selected phyton";;
4) echo "You selected c++";;
5) exit
esac
Quotations and quotes are important part of bash and bash scripting. Here are some bash quotes and quotations basics.
Before we start with quotes and quotations we should know something about escaping meta characters. Escaping will suppress a special
meaning of meta characters and therefore meta characters will be read by bash literally. To do this we need to use backslash "\" character.
Example:
#!/bin/bash
#when meta character such us "$" is escaped with "\" it will be read literally
echo \$BASH_VAR
# backslash has also special meaning and it can be suppressed with yet another "\"
echo "\\"
Single quotes in bash will suppress special meaning of every meta characters. Therefore meta characters will be read literally. It is not
possible to use another single quote within two single quotes not even if the single quote is escaped by backslash.
#!/bin/bash
# meta characters special meaning in bash is suppressed when using single quotes
echo '$BASH_VAR "$BASH_VAR"'
16.3. Double Quotes
Double quotes in bash will suppress special meaning of every meta characters except "$", "\" and "`". Any other meta characters will be
read literally. It is also possible to use single quote within double quotes. If we need to use double quotes within double quotes bash can
read them literally when escaping them with "\". Example:
#!/bin/bash
#!/bin/bash
#!/bin/bash
let RESULT1=$1+$2
echo $1+$2=$RESULT1 ' -> # let RESULT1=$1+$2'
declare -i RESULT2
RESULT2=$1+$2
echo $1+$2=$RESULT2 ' -> # declare -i RESULT2; RESULT2=$1+$2'
echo $1+$2=$(($1 + $2)) ' -> # $(($1 + $2))'
# bash subtraction
let SUBTRACTION=7-8
echo "7 - 8 =" $SUBTRACTION
# bash multiplication
let MULTIPLICATION=5*8
echo "5 * 8 =" $MULTIPLICATION
# bash division
let DIVISION=4/2
echo "4 / 2 =" $DIVISION
# bash modulus
let MODULUS=9%4
echo "9 % 4 =" $MODULUS
#!/bin/bash
# Simple linux bash calculator
echo "Enter input:"
read userinput
echo "Result with 2 digits after decimal point:"
echo "scale=2; ${userinput}" | bc
echo "Result with 10 digits after decimal point:"
echo "scale=10; ${userinput}" | bc
echo "Result as rounded integer:"
echo $userinput | bc
18. Redirections
#!/bin/bash
To prove that STDOUT is redirected to STDERR we can redirect script's output to file:
#!/bin/bash
cat $1 2>&1
To prove that STDERR is redirected to STDOUT we can redirect script's output to file:
The simple way to redirect a standard output ( stdout ) is to simply use any command, because by default stdout is automatically
redirected to screen. First create a file "file1":
$ touch file1
$ ls file1
file1
As you can see from the example above execution of ls command produces STDOUT which by default is redirected to screen.
$ ls
file1 STDOUT
$ ls file2
ls: cannot access file2: No such file or directory
In the following example we will redirect the standard error ( stderr ) to a file and stdout to a screen as default. Please note that STDOUT
is displayed on the screen, however STDERR is redirected to a file called STDERR:
$ ls
file1 STDOUT
$ ls file1 file2 2> STDERR
file1
$ cat STDERR
ls: cannot access file2: No such file or directory
It is also possible to redirect STDOUT and STDERR to the same file. In the next example we will redirect STDOUT to the same descriptor
as STDERR. Both STDOUT and STDERR will be redirected to file "STDERR_STDOUT".
$ ls
file1 STDERR STDOUT
$ ls file1 file2 2> STDERR_STDOUT 1>&2
$ cat STDERR_STDOUT
ls: cannot access file2: No such file or directory
file1
The above example can be reversed by redirecting STDERR to the same descriptor as SDTOUT:
$ ls
file1 STDERR STDOUT
$ ls file1 file2 > STDERR_STDOUT 2>&1
$ cat STDERR_STDOUT
ls: cannot access file2: No such file or directory
file1
$ ls
file1 STDERR STDOUT
$ ls file1 file2 &> STDERR_STDOUT
$ cat STDERR_STDOUT
ls: cannot access file2: No such file or directory
file1
or
Thank you.
• Reply • Share ›
Deployment of Kippo SSH Honeypot on Ubuntu Rename all file names from uppercase to
Linux lowercase characters
1 comment • 2 months ago• 1 comment • 3 months ago•
Ben Sherkat — I get this when i try to run it can you Red Cricket — awesome! thank you!
please help. kippo@kali:/root/kippo-0.5$ ./start.sh
Starting kippo in background...Unhandled Error …
How to disable User Accounts in Linux Linux DOSBox emulator and DOS games now
1 comment • 2 months ago• free to download
saurabh rathor — I have a local user which is able to 1 comment • 3 months ago•
access directory but not able to list (ls) files in directory Fernando Basso — I'll give it a try. This stuff is
(permission denied). User has all rights. However, if … wonderful. Thanks for posting.
Contact us (http://www.linuxcareer.com/contact-us)
(floss-technical-writer-linuxconfig-org)