Search notes:

Shell script

Check if at least n arguments are present

$# stores the number of arguments that were given when executing a shell script. Thus, it's possible to check if at least a given number of arguments are present.
The following fragment checks if at least 3 arguments were passed:
if [ $# -lt 3 ]; then
    echo Error: At least 3 arguments are required.
    exit 1
fi

# … rest of the shell script …

String comparison

Check if a string starts with a given string

if [   abcdef =  abc  ];  then echo matched; else echo did not match; fi
if [   abcdef =  abc* ];  then echo matched; else echo did not match; fi
if [   abcdef == abc* ];  then echo matched; else echo did not match; fi
if [[  abcdef == abc* ]]; then echo matched; else echo did not match; fi    # matched
if [[  abcdef =  abc* ]]; then echo matched; else echo did not match; fi    # matched
if [[ xabcdef =  abc* ]]; then echo matched; else echo did not match; fi
Note, [[ is not available in /bin/sh, so the following construct is an alternative for checking if a string starts with a given string:
case $var in
  "$prefix"*) echo The variable starts with the prefix.         ;;
  *)          echo The variable does not start with the prefix. ;;
esac

getopts

while getopts fx:h OPTION; do

  case $OPTION in
    f)
       echo f was specfied
       ;;
    x)
       echo x was specified with value $OPTARG
       ;;
    h)
       echo $0 [-f] [-x value] [-h]
       ;;
    esac

done

echo OPTIND=$OPTIND
$ ./script
OPTIND=1

$ ./script -h
./script [-f] [-x value] [-h]
OPTIND=2

$ ./script -x
./script: option requires an argument -- x
OPTIND=2

$ ./script -x foo
x was specified with value foo
OPTIND=3

$ ./script -xbar
x was specified with value bar
OPTIND=2

$ ./script -f -x baz
f was specfied
x was specified with value baz
OPTIND=4
The value of OPTIND can be used to «shift away» the option arguments so that the required arguments can be processed:
shift $((OPTIND-1))

Determine directory where script is located

dir="$(dirname "$(readlink -f "$0")")"

Remove given extension from a filename

The following prints readme:
filename=readme.txt
echo ${filename%.txt}

Check if program/command/executable is present

if command -v cmake &> /dev/null; then
    echo cmake was found
else
    echo cmake was not found
fi

Prevent the script from being stopped with Ctrl-C

#!/bin/bash

trap "echo Ctrl-C detected, but ignored. Use 'kill -9 $$' to kill it." SIGINT

echo "Script is running. Press Ctrl-C to try to stop it."

for i in {1..4}; do
    echo "Loop $i"
    /bin/sleep 5
done

trap - SIGINT
echo "Default behavior of Ctrl-C is restored. Press Ctrl-C to stop the script now."

while true; do
    /bin/sleep 1
done
Note: when the user presses ctrl-c, the shell script is not stopped, but the foreground process initiated by the script (here: /bin/sleep) is.

See also

shebang
shell
ShellCheck is a static analyzer tool for shell scripts.

Index