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"
while ; do
done
# Logic goes here
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
||
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
_FOOBAR_in bright (
01
) red (31
). After that, it resets to default settings (00
) and prints a newline caracter (\n
)
# With %s placeholder
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.
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.
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 |