Shell Scripting Gotchas and the Bad Part
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.
x = 5PASS, NO SPACE
x=5
The for
loop is separated by space too.
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.
hello
FOO
The alternative operator to support indent <<-
needs tab NOT space.
The Bad Part Bash function argument is meaningless
echo "$a $b"
}
Something like this will fail. Bash take the argument through $1
, $2
,…
So we need to assign it like this.
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.
... do something ...
return 0
}
You need to assign value to Global Variable OMG ! yes it is !