Skip to content
Laviyx Learn

Try

Linux and Bash Cheat Sheet

Moving around, files, grep and find, pipes, text tools, permissions, processes, services, disks, networking, cron and Bash scripting.

Updated

Move around#

Terminal
pwd                     # where am I
ls -lah                 # list everything, with details
cd folder               # enter a folder
cd ..                   # up one level
cd -                    # previous folder
cd ~                    # home

Files#

Terminal
mkdir -p a/b/c          # create nested folders
touch file.txt          # create an empty file
cp -r src dest          # copy a folder
mv old new              # move or rename
rm -r folder            # delete; there is no recycle bin
ln -s target link       # symbolic link
cat file                # print a file
less file               # scroll (q quits)
head -n 5 file          # first lines
tail -f app.log         # follow a growing file
wc -l file              # count lines
Terminal
grep -rin "text" src    # recursive, ignore case, line numbers
grep -v "DEBUG" app.log # lines that do not match
grep -E "WARN|ERROR" f  # extended regex
find . -name "*.py"     # by name
find . -type f -size +100M
find . -mtime -1        # changed in the last day
find . -name "*.tmp" -delete

Pipes and redirection#

Terminal
cmd > file              # write to a file
cmd >> file             # append
cmd 2> err.txt          # errors to a file
cmd > all.txt 2>&1      # both to a file
cmd 2> /dev/null        # discard errors
cmd1 | cmd2             # pipe
cmd | tee file          # see it and save it
echo "$(date)"          # command substitution

Text tools#

Terminal
sort -t, -k2 -nr f      # sort by column 2, numeric, descending
sort | uniq -c | sort -nr | head   # top N
cut -d, -f1,3 file      # columns
tr 'a-z' 'A-Z'          # translate characters
sed 's/old/new/g' file  # replace
sed -i.bak 's/a/b/' f   # replace in place, with backup
awk '{print $1}' file   # first column
awk -F, '$3 > 10' file  # filter rows
awk '{s += $2} END {print s}' file   # sum a column

Permissions#

NumberLettersUse
755rwxr-xr-xScripts, folders
644rw-r--r--Normal files
700rwx------Private folders
600rw-------Private files, SSH keys
Terminal
chmod 755 file          # set by number
chmod +x script.sh      # add execute
chown user:group file   # change owner
sudo command            # run as root
id                      # my user and groups
sudo usermod -aG docker asha   # add to a group

Processes and services#

Terminal
ps aux | grep nginx     # find a process
pgrep -a nginx
top                     # live view
kill PID                # ask to stop
kill -9 PID             # force
command &               # run in the background
nohup command &         # survive logout
systemctl status nginx
sudo systemctl restart nginx
sudo systemctl enable --now nginx
journalctl -u nginx -f  # follow logs

System#

Terminal
df -h                   # free disk space
du -sh *                # folder sizes
du -h --max-depth=1 | sort -hr
free -h                 # memory
uptime                  # load
uname -a                # kernel
sudo apt update && sudo apt install name
tar -czf a.tar.gz folder    # create
tar -xzf a.tar.gz -C dest   # extract
tar -tzf a.tar.gz           # list

Network#

Terminal
ip -br addr             # addresses
ss -ltn                 # listening ports
sudo ss -ltnp           # with programs
nc -zv host 443         # test a port
dig +short example.com  # DNS
curl -sI https://example.com    # headers
curl -s -o /dev/null -w "%{http_code}\n" URL
ssh user@host
scp file user@host:path
rsync -az src/ user@host:dest/

cron#

Text
* * * * *  command
│ │ │ │ └─ day of week (0-6, Sunday is 0)
│ │ │ └─── month
│ │ └───── day of month
│ └─────── hour
└───────── minute

*/5 * * * *   every 5 minutes
30 2 * * *    02:30 every day
0 9 * * 1-5   09:00, Monday to Friday

Bash basics#

Terminal
#!/usr/bin/env bash
set -euo pipefail

name="Asha"                # no spaces around =
echo "Hello, ${name}"      # always quote
count=$(ls | wc -l)        # command output
echo $((count + 1))        # arithmetic
echo "${PORT:-8080}"       # default value

Conditions and loops#

Terminal
if [[ -f "$file" ]]; then
  echo "exists"
elif (( count > 5 )); then
  echo "many"
else
  echo "none"
fi

for f in *.txt; do echo "$f"; done

while IFS=, read -r a b; do
  echo "$a"
done < data.csv

case "$1" in
  start) echo "go" ;;
  *) echo "usage" ;;
esac

Functions and arguments#

Terminal
add() {
  local a="$1" b="$2"
  echo $((a + b))
}
total=$(add 2 3)
VariableMeaning
$1, $2Arguments
$#Number of arguments
"$@"All arguments
$?Last exit code
$$PID of this shell
$!Last background PID

Tests#

TestTrue when
-f file, -d dir, -e pathIs a file, a folder, or exists
-z "$a", -n "$a"Empty, not empty
"$a" == "$b"Text is equal
$a -eq $b, -gt, -ltNumber comparisons

Strings#

Terminal
${#v}          # length
${v:0:4}       # substring
${v//a/b}      # replace all
${f##*/}       # file name from a path
${f%/*}        # folder from a path
${f%.*}        # remove the extension
${v^^}         # upper case

Want the full explanations? Go to the Learn Linux and Bash Scripting course →