Skip to content

08_Bash Scirpt

Davood Dorostkar edited this page Dec 17, 2023 · 1 revision

Functions

Definition

use either one:

function_name () {
  commands
}
function_name () { commands; }
function function_name {
  commands
}
function function_name { commands; }

Variable Scopes

var1='A'
var2='B'

my_function () {
  local var1='C'
  var2='D'
  echo "Inside function: var1: $var1, var2: $var2"
}

Return Values

first option:

my_function () {
  func_result="some result"
}

second option:

my_function () {
  local func_result="some result"
  echo "$func_result"
}

return error code:

my_function () {
  echo "some result"
  return 55
}

Pass Arguments

greeting () {
  echo "Hello $1"
}

greeting "Joe"

Check if file/directory exists:

link

test -f /etc/resolv.conf && echo "$FILE exists."
[ -f /etc/resolv.conf ] && echo "$FILE exists."
[[ -f /etc/resolv.conf ]] && echo "$FILE exists."

Comparisons

link

if [ "$a" -gt "$b" ]
(("$a" <= "$b"))

Exit loops

link

#!/bin/bash

i=0

while [[ $i -lt 11 ]] 
do
        if [[ "$i" == '2' ]]
        then
                break
        fi
        ((i++))
done

echo "Done!"
Clone this wiki locally