Skip to content

Instantly share code, notes, and snippets.

@pwillis-els
Last active May 7, 2020 19:14
Show Gist options
  • Save pwillis-els/0c1fdaa89a269a9ce1c79c6693beb7df to your computer and use it in GitHub Desktop.
Save pwillis-els/0c1fdaa89a269a9ce1c79c6693beb7df to your computer and use it in GitHub Desktop.
Bash cheat sheet

Bash Cheat Sheet

Strings

Check if a substring exists in a string

name="somethinglong"
substr="thing"
if [ ! "${name/$substr/}" = "$name" ] ; then
    echo "'$substr' found in '$name'"
else
    echo "'$substr' not found in '$name'"
fi

Arrays

Length

a=(1 2 3 4)
echo ${#a[@]}

Associative Arrays

declare -A my_dict
my_dict[foo]=bar
my_dict[some]=thing
my_dict[one]=two
for key in "${!my_dict[@]}" ; do
    printf "key $key value ${my_dict[$key]}\n"
done

Input

Read a line of input

  • You almost always want to use read -r rather than just read.
    read -r COMPLEX_STRING
    printf "$COMPLEX_STRING\n"

Read line by line, in the current shell

  • If you pipe a command directly to a while read ... loop, it will spawn a new subshell which cannot interact with the parent shell (for example, to change global variables).
    GLOBAL_VAL=1
    printf "line1\nline2\nline3\n" | while read -r LINE ; do
        GLOBAL_VAL=$(($GLOBAL_VAL+1))
    done
    echo $GLOBAL_VAL
    This will print 1.
  • To loop in the current shell, read from the pipe using file descriptor redirection.
    GLOBAL_VAL=1
    while read -r LINE ; do
        GLOBAL_VAL=$(($GLOBAL_VAL+1))
    done < <( printf "line1\nline2\nline3\n" )
    echo $GLOBAL_VAL
    This will print 4.

Output

Printing output lines

  • Using echo is usually not what you want:
    • It can fail if first argument ends up starting with "-".
    • Not all echos support the -e or -n option.
  • Usually you want to use printf.
    • To print the literal string "foo\nbar":
      printf "%s" "foo\nbar"
    • To print the string and change "\n" into a newline character:
      printf "foo\nbar"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment