Shell

Updated: 2021-11-24

POSIX Shell

The POSIX (the Portable Operating System Interface) shell is the standard Unix shell, i.e. it was formally defined and shipped in a published standard, it has many competing implementations on many different operating systems, but are compatible.

POSIX shell is basically Bourne shell, lives at the standardized location /bin/sh.

The POSIX standard does not recognize long flags like grep --file=FILE, but only the short flags like grep -f. (Because it does not define getopt_long function, only getopt function).

Bash: Bourne Again Shell

In many Linux distros, bash is the default shell, and /bin/sh is symlinked to /bin/bash.

Bash is not standardized, but there's only one implementation of bash (i.e. bash is defined by its implementation).

Shebang

The #! is called a shebang. Scripts will execute using the interpreter specified on a first line.

Make Shell Script Portable

If you use the POSIX shell /bin/sh, just add #!/bin/sh to the top of your script. The location is standardized.

If you use other shells, e.g. bash, use #!/usr/bin/env bash instead of #!/bin/bash as shebang. Because bash is not always in the same location. If you have multiple versions of a shell installed, use env will make sure the first executable in the PATH will be used.

Set Environment Variable

$ x="hello" y="world" bash -c 'echo $x $y'
hello world

bash -c: "commands are read from the first non-option argument command_string. If there are arguments after the command_string, the first argument is assigned to 0andanyremainingargumentsareassignedtothepositionalparameters.Theassignmentto0 and any remaining arguments are assigned to the positional parameters. The assignment to 0 sets the name of the shell, which is used in warning and error messages."