Bash script tutorial

Serial tutorial written bash script in linux. Learn with us such as  “variable, String quotes, Conditional execution, Functions, Shell execution, Conditionals, Parameter expansions, Loops, Arrays, Options, Miscellaneous” in bash script. Bash script the essential for DevOps Roles.

Bash script

For example the define bashscript.sh file

#!/bin/bash
_NAME="HuuPV"
echo "Hello HuuPV"

Bash script execute file

Step 1: The modify execute file with chmod command

[huupv@huupv devopsroles]$ chmod +x bashscript.sh

Step 2: run execute file

[huupv@huupv devopsroles]$ ./bashscript.sh

Variables in bash script

_NAME="HuuPV"
echo $_NAME # --> HuuPV
echo "$_NAME" # --> HuuPV
echo "${_NAME}!" # --> HuuPV!

String quotes in bash script

_NAME="HuuPV"

Shell execution in bash script

echo "date is `date +%y%m%d`" # --> date is 180722

or

echo "date is $(date +%y%m%d)" # --> date is 180722

Parameter expansions

_NAME="HuuPV"

Substitution PV to pv

${_NAME/PV/pv} #=> "Huupv"

Slicing string HuuPV to Hu

${_NAME:0:2} #=> "Hu"
${_NAME::2} #=> "Hu"

Set Variable String STR=”/path/to/foo.txt”

echo ${STR%.txt} #=> /path/to/foo
echo ${STR%.txt}.o #=> /path/to/foo.o
echo ${STR##*.} #=> txt (extension)
echo ${STR#*/} #=> path/to/foo.txt
echo ${STR##*/} #=> foo.txt or basename ${STR}
echo ${STR/foo/bar} #=> /path/to/bar.txt
dirname ${STR} #=> /path/to (dirpath)

Length of $FOO variable

${#FOO}

Basic Substitution

${FOO%suffix} Remove suffix
${FOO#prefix} Remove prefix
${FOO%%suffix} Remove long suffix
${FOO##prefix} Remove long prefix
${FOO/from/to} Replace first match
${FOO//from/to} Replace all
${FOO/%from/to} Replace suffix
${FOO/#from/to} Replace prefix

Loops in bash script

basic for loop

for i in /tmp/*; do
  echo $i
done

Forever for loop

while true; do
···
done

Ranges for loop

for i in {1..5}; do
  echo "Welcome $i"
done

Reading lines for loop

cat file.txt | while read line; do
  echo $line
done

Functions in bash script

Define functions

f_func() {
  echo "hello"
}

or same as above

function f_func() {
  echo "hello"
}

Returning values

f_func() {
  local myresult='10'
  echo $myresult
}
result=$(f_func)

Arguments

$# Number of arguments
$* All arguments
$@ All arguments, starting from first
$1 First argument

Bash script Arrays

Defining arrays

arrayName=('Huu' 'Phan' 'DevopsRoles')
arrayName[0]="Huu"
arrayName[1]="Phan"
arrayName[2]="DevopsRoles"

Working with arrays

echo ${arrayName[0]} # Element #0
echo ${arrayName[@]} # All elements, space-separated
echo ${#arrayName[@]} # Number of elements
echo ${#arrayName} # String length of the 1st element
echo ${#arrayName[3]} # String length of the Nth element
echo ${arrayName[@]:3:2} # Range (from position 4, length 2)

Iteration in array

for i in "${arrayName[@]}"; do
  echo $i
done

Bash script Case switch

case "$1" in
  start | stop)
  nginx start
  ;;

  *)
  echo "Usage: $0 {restart|status}"
  ;;
esac

 

Keep reading. I will update later!