Shell Scripting Gotchas and the Bad Part

tanut aran
2 min readMay 16, 2021

--

Credit: wikipedia

Gotchas

File need to end with \n Blank line

Space

Bash need space to evaluate. Thing that look usual in other language can be syntax error in bash.

ERROR command x not found
x = 5
PASS, NO SPACE
x=5

The for loop is separated by space too.

for i in "${arr[@]}"; do; echo $i; doneWork just like
for i in 1 2 3 "foo" "bar"; do; echo $i; done
for i in {1..100}; do; echo $i; done

Compare String vs Int

For number, Bash does not have <,>,<=,>= but rather -lt, -gt, -le, -ge

For string, Bash use =, != for comparing. For exist and not exist use -n, -z

Here-document

The ending of here document need to be first thing the line. In the example below, FOO need to be at the beginning of the line without space or tab.

cat << FOO
hello
FOO

The alternative operator to support indent <<- needs tab NOT space.

The Bad Part

Bash function argument is meaningless

bash_function(a,b) {
echo "$a $b"
}

Something like this will fail. Bash take the argument through $1 , $2 ,…

So we need to assign it like this.

function bash_function {
local a=$1
local b=$2
... do other thing ...
}

To remind me of this fact, I prefer syntax of function ... { } than the one with (). One good part is Bash at least have local function scope.

Bash function cannot return value

Although Bash has return keyword, it doesn’t work as usual. It can only return 0-255 exit status where 0 mean success.

bash_function() {
... do something ...
return 0
}

You need to assign value to Global Variable OMG ! yes it is !

--

--

tanut aran
tanut aran

Written by tanut aran

Co-founder and Coder at work !

No responses yet