bash and Linux CLI Utilities Cheatsheet
This is NOT a first-time learning resource. Some parts are intentionally out of order and kept as.
Resources
References:
- Learn X in Y minutes - bash
(learnxinyminutes.com)
- Learn X in Y minutes - sed
(learnxinyminutes.com)
Tutorials:
bash
Basics and I/O
$ ./demo.sh foo bar baz
#!/usr/bin/env bash
set -v # Print commands as they are run.
echo "$#" # "3" (number of args)
echo "$@" # "foo bar baz"
echo "$0" # "./demo.sh"
echo "$1" # "foo"
echo "$2" # "bar"
# Read stdin into new variable $name
echo "What is your name?"
read name
echo "Hello, $name!"
# Read contents of a file into a variable
filecontents=$(cat myfile.txt)
echo "$filecontents"
Variables & Assignment
# Variable assignment must have no space around the `=` character.
my_var1="lmao ayy"
my_var2=$(printf "%s %d\n" "hello" 123) # my_var3 becomes "hello 123"
# When in doubt, use double-quotes for variable expansion.
echo "$my_var1" # "lmao ayy"
echo "${#my_var1}" # "8" (string length)
echo "${my_var1:2:5}" # "ao ay"
echo "${my_var1: -2}" # "yy" (the space is required)
echo "${my_var1/ayy/dab}" # "lmao dab"
other_var="my_var1"
echo "${!other_var}" # "lmao ayy"
# Default value if empty/nonexistent
echo "${i_dont_exist:-"foo"}" # "foo"
echo "${i_dont_exist:-$my_var1}" # "lmao ayy"
echo "${my_var1:-"foo"}" # "lmao ayy"
##################################################
my_array=(apple banana orange lemon)
echo "${my_array[@]}" # "apple banana orange lemon"
echo "${#my_array[@]}" # "4"
echo "${my_array[0]}" # "apple"
echo "${my_array[1]}" # "banana"
echo "${my_array[@]:1:2}" # "banana orange" (same slicing as string)
##################################################
echo {1..10} # "1 2 3 4 5 6 7 8 9 10"
echo {a..g} # "a b c d e f g"
#echo {$x..$y} # CAN'T USE VARIABLES
Structure & Control Flow
echo "first"; echo "second"
echo "always executes" || echo "only executes if first command fails"
echo "always executes" && echo "only executes if first command does not fail"
my_arr=(apple banana orange lemon)
for v in ${my_arr[@]}; do
echo $v
done
str1="foo"
if [[ $str1 == "bar" ]]; then
echo "this is true"
else
echo "this is false"
fi
num1=12
if [[ $str1 != "bar" ]] && [[ $num1 -eq 12 ]]; then
echo "this is true"
fi
Summary of Basic CLI Utilities
TODO: Whirlwind tour of everything including sed and awk.sed
TODO: Thisawk
TODO: ThisSome Common Sysadmin Utilities
TODO: Whirlwind tour of everything including sed and awk.TODO
TODO:jobs
, fg
, bg
, kill