guest@6admin.io:~$

Bash: Memento

A memo, not a tutorial. The bash lines you look up every time because you do not type them often enough to remember, but often enough to know they exist.

Substitutions

# Replace the first occurrence
${var/old/new}
# Replace all occurrences
${var//old/new}
# Remove the shortest pattern from the start
${var#pattern}
# Remove the shortest pattern from the end
${var%pattern}
# String length
${#var}
# Default value if empty
${var:-default}
# Assign if empty
${var:=default}
# Error if empty
${var:?message}

Arrays

declare -a tab
tab[0]="first"
tab+=(second third)
echo ${tab[@]}
echo ${#tab[@]}
echo ${tab[1]}
# Available indices
echo ${!tab[@]}

Redirections

cmd > file       # stdout to file (overwrites)
cmd >> file      # stdout to file (appends)
cmd 2> file      # stderr to file
cmd &> file      # stdout + stderr to file
cmd 2>&1         # stderr to stdout
cmd > /dev/null 2>&1  # full silence
cmd < file       # stdin from file

Loops

for i in $(ls); do echo "$i"; done
for i in {1..10}; do echo "$i"; done
while read line; do echo "$line"; done < file

Tests

[[ -f file ]]    # exists and is a regular file
[[ -d dir ]]     # exists and is a directory
[[ -s file ]]    # exists and is not empty
[[ -x file ]]    # executable
[[ "$a" == "$b" ]]  # string equality
[[ $n -eq $m ]]     # numeric equality
[[ $n -lt $m ]]     # less than

That is all. The rest is learned with man bash (EXPANSION section), but these lines are the ones you paste into a file and source.