Hi there,

in this little HowTo session I’m gonna show what I’ve experienced with shell scripts (sh) and what needed to be changed, since not everyone runs bash!

Personally I haven’t read any book about it (yet), you might give me a tip which one is good?
Shell programming books on Amazon

If you KNOW you want to use bash, stop here and write perfectly fine bash code! 😉

 

Don’t use double brackets! [[ ]]

They are not compatible with other shells.
Instead wrap your expression in single brackets and quote the expression

if [ -z "$1" ]

instead of

if [[ -z $1 ]]

 

The sudo check
if [ $(id -u) != 0 ]
  then
    print "Please run this script as root\n"
    exit 1
fi

Makes a negative root check.

 

Need newlines when printing something?

Normally I use echo with the -e option, which is not available.
Instead you could try

printf "Your string with\n newline"

 

Leave the function word out

When declaring a function just use

message() {
  printf "$1\n"
}

 

Use #!/bin/sh as your hashbang

Make sure you do not use #!/bin/bash.

 

Wrap your commands right

A real POSIX shell only supports

`command`

 
 
Found more stuff? Comment it, and I’ll add it.
Cheers!

HowTo: Make your shell script (more) POSIX compatible
The short URL of this article is: https://dustpla.net/l7k9h
Tagged on:

Leave a Reply

Your email address will not be published. Required fields are marked *