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 file

echo "Hello HuuPV"

Bash script execute file

Step 1: The modify execute file with chmod command

[huupv@huupv devopsroles]$ chmod +x

Step 2: run execute file

[huupv@huupv devopsroles]$ ./

Variables in bash script

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

String quotes in bash script


Shell execution in bash script

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


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

Parameter expansions


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


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

Forever for loop

while true; do

Ranges for loop

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

Reading lines for loop

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

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


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

Bash script Arrays

Defining arrays

arrayName=('Huu' 'Phan' '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

Bash script Case switch

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

  echo "Usage: $0 {restart|status}"


Keep reading. I will update later!