Shell Scripting Gotchas and the Bad Part

Bash Jul 12, 2023
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 = 5PASS, 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 !

CODEMONDAY - Web App | Mobile App | Digital & IT Solution and Software Development Company
Realize your idea and ship it online. web application, website, mobile, Digital & IT Solution, desktop applications, e-commerce. Want your business to shine in the digital world? We are here to help.

Tags

TeamCMD

We are CODEMONDAY team and provide a variety of content about Business , technology, and Programming. Let's enjoy it with us.