Skip to content

bash scripting reference cards

qoolixiloop edited this page Mar 17, 2019 · 10 revisions

qool-bash-loop.wiki

'BASH' Shell-and-Command-Language Reference-Cards

💖 Welcome Dear Friend!

You are visiting the qoolixiloop Bash Wiki. Please read on, if you like to find out, how you can profit from it.
Enjoy!

⏳ TL;DR

Usually, Bash is only one of many programming languages Linux professionals use. Especially, if only used from time to time, switching to it again is easy, if one either has an eidetic memory or good reference cards at one's fingertips. For all those not like Sheldon Cooper the next section might be a real game changer.

📚 Reference Cards

The cards are based on the Advanced Bash-Scripting Guide, which can be downloaded from TLDP the Linux document project, or it may be found on many other web sites as well. The book is really good, but unfortunately, one of the most useful parts is buried in appendix B on page 793. That's why I decided to adapt the content so that it can be shared in GitHub's Markdown tables. Please click the button below and open the chapter you are interested in. Once the table or tables are open the Browser's search function can be used, to support you in finding, what you are looking for.

📖 show bash reference cards 📚

Table B-1. Special Shell Variables

📖 show special shell variables 📚
Variable Meaning
$0 Filename of script
$1 Positional parameter #1
$2 - $9 Positional parameters #2 - #9
${10} Positional parameter #10
$# Number of positional parameters
"$*" All the positional parameters (as a single word) (I)
"$@" All the positional parameters (as separate strings)
${#*} Number of positional parameters
${#@} Number of positional parameters
$? Return value
$$ Process ID (PID) of script
$- Flags passed to script (using set)
$_ Last argument of previous command
$! Process ID (PID) of last job run in background

(I) Must be quoted, otherwise it defaults to $@.

📚

Table B-2. TEST Operators: Binary Comparison

📖 show test operators 📚
Operator Meaning Operator Meaning
Arithmetic Comparison within single [ ... ] or double parentheses ... String Comparison single [ ... ] or double parentheses ...
-eq Equal to = Equal to
. . == Equal to
-ne Not equal to != Not equal to
-lt Less than \< Less than (ASCII) (I)
-le Less than or equal to
-gt Greater than \> Greater than (ASCII) (I)
-ge Greater than or equal to
. . -z String is empty
. . -n String is not empty
Arithmetic Comparison within double parentheses (( ... ))
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to

(I) If within a double-bracket ... test construct, then no escape \ is needed.

📚

Table B-3. TEST Operators: Files

📖 show test operators for files 📚
Operator Tests Whether Operator Tests Whether
Arithmetic Comparison within single [ ... ] or double parentheses ... String Comparison single [ ... ] or double parentheses ...
-e File exists -s File is not zero size
-f File is a regular file
-d File is a directory -r File has read permission
-h File is a symbolic link -w File has write permission
-L File is a symbolic link -x File has execute permission
-b File is a block device
-c File is a character device -g sgid flag set
-p File is a pipe -u suid flag set
-S File is a socket -k "sticky bit" set
-t File is associated with a terminal
-N File modified since it was last read F1 -nt F2 File F1 is newer than F2 (I)
-O You own the file F1 -ot F2 File F1 is older than F2 (I)
-G Group id of file same as yours F1 -ef F2 Files F1 and F2 are hard links to the same file (I)
!? NOT (inverts sense of above tests)?

(I) Binary operator (requires two operands).

📚

Table B-4. Parameter Substitution and Expansion

📖 show parameter substitution and expansion 📚
Expression Meaning
${var} Value of var (same as $var)
${var-$DEFAULT} If var not set, evaluate expression as $DEFAULT (I)
${var:-$DEFAULT} If var not set or is empty, evaluate expression as $DEFAULT (I)
${var=$DEFAULT} If var not set, evaluate expression as $DEFAULT (I)
${var:=$DEFAULT} If var not set or is empty, evaluate expression as $DEFAULT I)
${var+$OTHER} If var set, evaluate expression as $OTHER, otherwise as null string
${var:+$OTHER} If var set, evaluate expression as $OTHER, otherwise as null string
${var?$ERR_MSG} If var not set, print $ERR_MSG and abort script with an exit status of 1.(I)
${var:?$ERR_MSG} If var not set, print $ERR_MSG and abort script with an exit status of 1.(I)
${!varprefix*} Matches all previously declared variables beginning with varprefix
${!varprefix@} Matches all previously declared variables beginning with varprefix

(I) If var is set, evaluate the expression as $var with no side-effects. Note that some of the above behavior of operators has changed from earlier versions of Bash.

📚

Table B-5. String Operations

📖 show string operations 📚
Expression Meaning
${#string} Length of $string
${string:position} Extract substring from $string at $position
${string:position:length} Extract $length characters substring from $string at $position [zero-indexed]
${string#substring} Strip shortest match of $substring from front of $string
${string##substring} Strip longest match of $substring from front of $string
${string%substring} Strip shortest match of $substring from back of $string
${string%%substring} Strip longest match of $substring from back of $string
${string/substring/replacement} Replace first match of $substring with $replacement
${string//substring/replacement} Replace all matches of $substring with $replacement
${string/#substring/replacement} If $substring matches front end of $string, substitute $replacement for $substring
${string/%substring/replacement} If $substring matches back end of $string, substitute $replacement for $substring
expr match "$string" '$substring' Length of matching $substring (I) at beginning of $string
expr "$string" : '$substring' Length of matching $substring (I) at beginning of $string
expr index "$string" $substring Numerical position in $string of first character in $substringI)that matches [0 if no match, first character counts as position 1]
expr substr $string $position $length Extract $length characters from $string starting at $position [0 if no match, first character counts as position 1]
expr match "$string" '\($substring\)' Extract $substring (I) searching from beginning of $string
expr "$string" : '\($substring\)' Extract $substring (I), searching from beginning of $string
expr match "$string"'.*\($substring\)' Extract $substring (I) searching from end of $string
expr "$string" : '.*\($substring\)' Extract $substring (I) searching from end of $string

(I) Where $substring is a Regular Expression.

📚

Table B-6. Miscellaneous Constructs

📖 show summary for miscellaneous constructs 📚
Expression Interpretation
Brackets
if [ CONDITION ] Test construct; spaces needed
if [[ CONDITION ]] Extended test construct; spaces needed
Array[1]=element1 Array initialization
[a-z] Range of characters within a Regular Expression
Curly Brackets
${variable} Parameter substitution
${!variable} Indirect variable reference
{ command1; command2; . . . commandN; } Block of code
{string1,string2,string3,...} Brace expansion
{a..z} Extended brace expansion
{} Text replacement, after find and xargs
Parentheses
( command1; command2 ) Command group executed within a subshell
Array=(element1 element2 element3) Array initialization
result=$(COMMAND) Command substitution, new style
>(COMMAND) Process substitution
<(COMMAND) Process substitution
Double Parentheses
(( var = 78 )) Integer arithmetic
var=$(( 20 + 5 )) Integer arithmetic, with variable assignment
(( var++ )) C-style variable increment
(( var-- )) C-style variable decrement
(( var0 = var1<98?9:21 )) C-style ternary operation
Quoting
"$variable" "Weak" quoting
'string' 'Strong' quoting
Back Quotes
result=`COMMAND` Command substitution, classic style

Table Syntax Summary for Arrays

📖 show summary for arrays 📚
Expression Interpretation
a=(word1 word2 "$word3" ...) Initialize an array from a word list, indexed starting with 0 unless otherwise specified.
a=(*.png *.jpg) Initialize an array with filenames.
a[i]=word Set one element to word, evaluating the value of i in a math context to determine the index.
a[i+1]=word Set one element, demonstrating that the index is also a math context.
a[i]+=suffix Append suffix to the previous value of a[i] (bash 3.1).
a+=(word ...) # append
a+=([3]=word3 word4 [i]+=word_i_suffix) # modify
unset 'a[i]' Unset one element. Note the mandatory quotes (a[i] is a valid glob).
"${a[i]}" `Reference one element.
"$(( a[i] + 5 ))" Reference one element, in a math context.
"${a[@]}" Expand all elements as a list of words.
"${!a[@]}" Expand all indices as a list of words (bash 3.0).
"${a[\*]}" Expand all elements as a single word, with the first char of IFS as separator.
"${#a[@]}" Number of elements (size, length).
"${a[@]:start:len}" Expand a range of elements as a list of words, cf. string range.
"${a[@]#trimstart}" "${a[@]%trimend}"
"${a[@]//search/repl}" etc. Expand all elements as a list of words, with modifications applied to each element separately.
declare -p a Show/dump the array, in a bash-reusable form.
mapfile -t a < stream Initialize an array from a stream (bash 4.0).
readarray -t a < stream Same as mapfile.
"$a" Same as "${a[0]}". Does NOT expand to the entire array. This usage is considered confusing at best, but is usually a bug.

📚

📚

🌎 Links

Please click the button below, if you would like to navigate to another page of this repository.

📖 click me to see the links 🌎

Bash Code: Scripts to download
Bash Wiki: Home
Bash Wiki: Learning Bash from example
Bash Wiki: Small Bash Framework and Template
Bash Wiki: Bash Cheat-Sheet

🌎

💻 About me

My name is Roland Benz, I live in Zurich, Switzerland and decided spontaneously to dedicate my time and knowledge to some projects on GitHub. By clicking the button below you will get all the necessary information with respect to hiring and donations.

📖 please click me ...

💫

Hiring and Collaboration

There is a personal repository dedicated to hiring and collaboration. If you are located in Switzerland this is the place, where you can find some sort of CV and contact information.

Donations

The qoolixiloop repositories will constantly be filled with great content. This service to the general public comes as a huge effort from my side. In case you are a wealthy person or an executive of a big organization, not knowing, where to invest all the money that is pouring in, there is hope on the horizon. Below you will find my lonely and empty bank account, grateful and happy about any kind of attention.

💫

📖 show details for a bank transfer

💫

Details for a bank transfer to my account
Informations pour un virement bancaire sur mon compte
Detalles para una transferencia bancaria a mi cuenta
Angaben für eine Überweisungen auf mein Konto

💫 Details / Information / Detalles / Angaben
BIC (SWIFT-Code) of my bank POFICHBEXXX
BIC (SWIFT-Code) de ma banque POFICHBEXXX
BIC (SWIFT-Code) de mi banco POFICHBEXXX
BIC (SWIFT-Code) meiner Bank POFICHBEXXX
💫 💫
Name/Adresse of my bank PostFinance AG, Mingerstrasse 20, 3030 Bern, Switzerland
Nom et adresse de ma banque PostFinance AG, Mingerstrasse 20, 3030 Bern, Suisse
Nombre y dirección de mi banco PostFinance AG, Mingerstrasse 20, 3030 Bern, Suiza
Name/Adresse meiner Bank PostFinance AG, Mingerstrasse 20, 3030 Bern, Schweiz
💫 💫
My account number (IBAN) CH08 0900 0000 8007 4635 1
Mon numéro de compte CH08 0900 0000 8007 4635 1
Mi número de cuenta CH08 9000 0000 8007 4635 1
Meine Kontonummer (IBAN) CH08 0900 0000 8007 4635 1
💫 💫
My name and address Roland Benz, Felsber 2, 8052 Zurich, Switzerland
Mon nom et adresse Roland Benz, Felsber 2, 8052 Zurich, Suisse
Mi nombre y dirección Roland Benz, Felsberg 2, 8052 Zurich, Suiza
Mein Name und Adresse Roland Benz, Felsberg 2, 8052 Zürich, Schweiz

💫


qoolixiloop, 25. Nov. 2018