Shell snippets

The snippets on this site are intended for getting copied and being useful so please do that.

Argument parser

A simple argument parser for bash.

#!/bin/bash

# Settings variables go here
FOO="foo"

show_help() {
cat <<EOF
Usage: foo <<options>> <bar>

Blubber blah blah ...
EOF
}

while [[ "$#" -gt 0 ]]; do
	case "$1" in
		--foo) FOO="$2"; shift 2;;
		
		--help) show_help; exit 0;;
		*) printf "Unknown option: %s\n" "$1"; exit 1;;
	esac
done

# Logic goes here
echo "$FOO"

Hook helper

This little function calls its argument as an ad-hoc shellscript if it is non-empty, if it reurns a nonzero, one should call the default action.

# on fail do default action
run_hook() {
	[ -n "$1" ] && bash -c "$1"
}
Example usage of how this little helper is intended to be used
export VARIABLE_WHICH_IS_USEFUL_FOR_HOOK="something"
run_hook "$HOOK_COMMAND" || default_action

An example of this being used can be found in my dotfiles with the filedialog. (Fun fact: It was created for this script)

Escape Sequences (ANSI)

Ansi Escape squences can be achieved using printf or echo -e in shell scripts (I personally prefer printf).

I'll focus on Select Graphic Rendition (SGR) codes here, Wikipedia has a more complete list.

Setting Text Color and Effects

An example which prints out _FOOBAR_ in bright (01) red (31). After that, it resets to default settings (00) and prints a newline caracter (\n)
printf '\x1b[01;31m_FOOBAR_\x1b[00m\n'
# With %s placeholder
printf '\x1b[01;31m%s\x1b[00m\n' "_FOOBAR_"

As you can see in the example, multiple escape-codes can be chained in one sequence by delimiting them with a ;.

The \x1b part is an ASCII escape caracter it can also be written as \e, the [ tells the terminal that this is an ANSI Control Sequence Initiator (CSI) after that can come one or more codes. The sequence is finished by an m to tell the terminal that everything between the CSI and it are SGR codes.

If you are using escape sequences in your scripts: Please make sure that no information gets lost when those seqences are stripped, People with processing pipelines and screenreaders will thank (or at least not curse at) you.

Most commonly used codes
Code Code to reverse Effect
00 Reset all effects
Foreground color
30-37 39 Set the Foreground color
90-97 39 Set the Foreground color, bright variation
Background color
40-37 49 Set the Background color
100-107 49 Set the Background color, bright variation
Font effects
01 22 Bright text (usually bold and brighter color)
02 22 Dim text (usually only effect on color)
03 23 Italic text
04 24 Underlined text
05 25 Blinking text
07 27 Reverse forground and background color

Note: The leading zeros are not needed.

Colors

You may have noticed that the 3x, 4x, 9x, and 10x family of codes all use the last digit in the range from 0 to 7 as a color parameter.

Table of colors
Code Color
0 Black or Dark Grey
1 Red
2 Green
3 Yellow
4 Blue
5 Violet / Purple
6 Cyan or Turquoise
7 Light Grey or White