Variables
# Define
NAME="Mark"
# Use
echo "Hello $NAME"
echo $NAME
echo "${NAME}!"
String Quotes
- "Hi $NAME"Interpolated → Hi John
- 'Hi $NAME'Literal → Hi $NAME
Name="John"
echo "Hi $NAME" # Hi John
echo 'Hi $NAME' # Hi $NAME
Functions
myfunc() {
echo "hello $1"
}
# Alternate syntax
function myfunc() {
echo "hello $1"
}
myfunc "John"
Arguments & Special
- $#Number of arguments
- $*All arguments
- $1First argument
- $?Exit status
- $$PID of shell
- $0Script filename
- $!PID of last background task
Conditionals
- [[ -z STRING ]]Empty string
- [[ -n STRING ]]Not empty
- [[ STR == STR ]]Equal
- [[ STR != STR ]]Not equal
- [[ NUM -eq NUM ]]Equal (num)
- [[ NUM -lt NUM ]]Less than
- [[ NUM -gt NUM ]]Greater than
- [[ -e FILE ]]Exists
- [[ -f FILE ]]Is file
- [[ -d FILE ]]Is directory
- [[ -r FILE ]]Readable
- [[ -w FILE ]]Writeable
- [[ -x FILE ]]Executable
- [[ -s FILE ]]Size > 0
Loops
# Basic Loop
for i in /etc/rc.*; do
echo $i
done
# C-like Loop
for ((i=0; i<100; i++)); do
echo $i
done
# Range Loop
for i in {1..5}; do
echo "Welcome $i"
done
Arrays
Fruits=('Apple' 'Banana' 'Orange')
- ${Fruits[0]}First element
- ${Fruits[@]}All elements
- ${#Fruits[@]}Length
- ${Fruits[@]:3:2}Range
Redirection
- > filestdout to file
- >> filestdout append
- 2> filestderr to file
- 2>&1stderr to stdout
- &>/dev/nullSilence all
- < fileFeed stdin
String Manipulation
- ${STR,}Lowercase 1st
- ${STR,,}All lowercase
- ${STR^}Uppercase 1st
- ${STR^^}All uppercase
- ${#STR}String length
- ${STR:0:5}Substring
Conditional Execution
- cmd1 && cmd2Run if cmd1 succeeds
- cmd1 || cmd2Run if cmd1 fails
git commit && git push
git commit || echo "Failed"
Brace Expansion
- {A,B}.jsA.js B.js
- {1..5}1 2 3 4 5
- {a..z}a b c ... z
- {01..10}01 02 ... 10
History & Navigation
- !!Execute last command
- historyShow history
- pwdShow path
- cd -Previous directory
- cd ~Go to home