Bash cheat sheet
Shell scripting essentials for Bash.
Script basics
#!/usr/bin/env bash- First line of a script
set -euo pipefail- Stop on errors, unset variables and failed pipes
chmod +x script.sh && ./script.sh- Make executable and run
name="Ana"; echo "Hi $name"- Variable (no spaces around =)
echo "$1" "$@" "$#"- First argument, all arguments, count
$(command)- Use a command output as text
Conditions
if [ -f file ]; then ...; fi- File exists
[ -d dir ]- Directory exists
[ "$a" = "$b" ]- Strings equal (quote variables)
[ "$n" -gt 5 ]- Number greater than 5
cmd1 && cmd2- Run cmd2 only if cmd1 succeeds
cmd1 || cmd2- Run cmd2 only if cmd1 fails
Loops and functions
for f in *.txt; do echo "$f"; done- Loop over files
for i in {1..5}; do echo $i; done- Count 1 to 5
while read -r line; do ...; done < file- Read a file line by line
greet() { echo "Hi $1"; }- Define a function
Pipes and redirection
cmd1 | cmd2- Send the output of cmd1 to cmd2
cmd > file- Write output to a file (overwrite)
cmd >> file- Append output to a file
cmd 2> errors.log- Send errors to a file
cmd > out.log 2>&1- Send output and errors to one file
cmd < file- Read input from a file
Exit codes
echo $?- Exit code of the last command (0 is success)
exit 1- End the script with an error
trap "rm -f tmp" EXIT- Run cleanup when the script ends
Handy one-liners
grep -c "error" app.log- Count lines with a word
sort file | uniq -c | sort -nr- Frequency of each line
find . -name "*.log" -mtime +30 -delete- Delete logs older than 30 days (check without -delete first)
du -sh * | sort -h- Folders by size
history | grep ssh- Find a past command
Learn it properly