Bash Basic


Declare Variable

# basic assignment 
STR="Hello World!"
echo $STR  
 
NUMBER=4
echo $NUMBER  
 
# warning : space must not be used here for variable assignment
# this line  will call programe 'NUMBER' with parameter '=' and '4' 
NUMBER = 4
 
 
# initialisation from other variable
FIST_NAME="Linus"
LAST_NAME="Torvalds"
FULL_NAME=$FIST_NAME"_"$LAST_NAME
 
#  If variable not set or null, use default. ( VARIABLE is untouched )
FOO=${VARIABLE:-"Default value"}  
 
# If variable not set or null, set it to default.
FOO=${VARIABLE:=default}
 
# Equivalent to VARIABLE:=${VARIABLE:=default}
: ${VARIABLE:="DEFAULT_VALUE"}
 
 
# command substitution 
VAR=`echo 'hello world'`
var=$(echo 'hello world')
 
echo $VAR  
echo $var
 
TXT_FILES=$(find . -name *.txt)
echo $TXT_FILES
 
# partial initialisation from cmd
LOG_FILE=log_file_$(date +%Y_%m_%d).log
 
# variable can be unset to clear the value
unset VAR
unset LOG_FILE
 

Variable and Operation

 
 
# integer operation 
# incrementation 
var=5
var=$((var + 1))
echo $var
# div 
var=$((var / 2))
echo $var
 
# Using post or pre increment/decrement operator
((var++))
echo $var
 
((--var))
echo $var
 
# Using shorthand operator
(( val2 += 60 ))
echo $val2
 
# Calculate full mathematical expression
val=$((10*5+15))
echo $val
 
 
#  floating-point operation with ‘bc’ command 
echo "1/3" | bc -l
echo "scale=8; 2/3" | bc -l
# compute pi  = ( 4 * atan ( 1 ) )
echo "scale=100; 4*a(1)" | bc -l
 
# concatenation 
foo='hello'
bar='world !'
var=$foo" "$bar
 
echo $var
 
Control Structure


If ... Then ... Else If ... Else ... End If

 
 
# use -eq for equal
# use -ge for greater or equal
# use -gt for greater than
# use -le for lower or equal 
# use -lt for lower than
# see 'man test' for all case
 
#set temperature 
temperature=28
 
if [ $temperature -ge 40 ]
then
  echo "Burning"
elif [ $temperature -ge 30 ]
then
  echo "Hot"
elif [ $temperature -ge 18 ]
then
  echo "Warm"
else
  echo "Cold"
fi
 
# easier way 
if [ ($temperature > 40) ]
then
  echo "Burning"
elif [ ($temperature > 30) ]
then
  echo "Hot"
elif [ ($temperature > 18) ]
then
  echo "Warm"
else
  echo "Cold"
fi
 
# string comparison ( v1 )
if [ "$VAR1" = "$VAR2" ]; then
    echo "Strings are equal."
else
    echo "Strings are not equal."
fi
 
# string comparison ( v2 )
if [[ "$VAR1" == "$VAR2" ]]; then
    echo "Strings are equal."
else
    echo "Strings are not equal."
fi
 
# string comparison ( v3 ) with && and || operator
# cmd after '&&' is execute if the previous cmd succeeded 
# cmd after '||' is execute if the previous cmd failed 
[[ "string1" == "string2" ]] && echo "Equal" || echo "Not equal"
 
# string comparison ( v4 ) with reg expresion
if [[ "$FILE" =~ .*\.txt ]]; then
    echo "$FILE is a txt file"
else
    echo "$FILE is not a txt file"
fi
 
 
# check that VAR is empty
[[ -z $VAR ]] && echo "String is empty"
# check that VAR is not empty
[[ -n $VAR ]] && echo "String is not empty" 
 
# case for more complexe use case
VAR="Arch Linux"
case $VAR in
 
  "Arch Linux")
    echo -n "Arch"
    ;;
 
  Fedora | CentOS)
    echo -n "Red Hat"
    ;;
esac
 
 
# if file existe  : see 'man test' for all case
if [ -e $FILE ]
then
   process_file.sh $FILE
fi
 

Declare Loops

#Loop through number
 
for I in 1 2 3 4 5 ; do  echo $I ; date ; sleep 1 ;done
 
for I in $(seq 1 100) ; do  echo $I ; date ; sleep 1 ;done
 
for i in {1..100}
do
   echo $I
   date
   sleep 1
done
 
# c synctax
for (( I=1; I<=5; I++ ))
do  
   echo $I
   date
   sleep 1
done
 
 
#Loop through Files
 
for FILE in *; do
  # do something with $FILE
  echo "File: $FILE"
done
 
#For more control, use /usr/bin/file
 
for FILE in $(find ./ -name *.html -type f); do
  # do something with $FILE
  echo "HTML File: $FILE"
done
 
#Loop through Lines in a File
 
while read LINE; do
  # do something with $LINE
  echo "Line: $LINE"
done < /etc/hosts
 
#Loop through Words in a File
 
for WORD in $(cat /etc/hosts); do
  # do something with $WORD
  echo "Word: $WORD"
done
 
#Loop through Characters in a File
 
while read -n1 CHAR; do
  # do something with $CHAR
  echo "Character: $CHAR"
done < /etc/hosts
 
 
#Loop through file *.log and rename it to *.txt 
for F in $(find . -name *.log)
do
    echo $F
    mv $F ${F%.log}.txt
done
 
 
#Loop through server 
for s in server1 server2 server3
do
    echo "Server ${s}: $(ssh username@${s} hostname)"
done
 

Bash Trap : Control+C to exit script

Use the Bash builtin trap command to catch system signals. trap define the callback function.
#!/bin/bash
 
control_c_callback()
{
  echo -en "Exiting \n"
  cleanup
  exit
}
 
# trap keyboard interrupt 
trap control_c_callback  SIGINT
 
# main() loop
while true; do read x; done