ubuntu, updated
Pipes, redirects and operators
The shell operators | > >> < 2>&1 && || explained, plus the handful of one-liners for finding files, text and disk hogs.
The idea
Linux tools are small and do one thing. You combine them: the output of one becomes the input of the next. Every program has three streams:
| Stream | Number | Default |
|---|---|---|
| stdin (input) | 0 | keyboard |
| stdout (output) | 1 | screen |
| stderr (errors) | 2 | screen |
Pipes and redirects
| Syntax | Does |
|---|---|
a | b | Output of a becomes input of b |
cmd > file | Write output to file (overwrites) |
cmd >> file | Append output to file |
cmd 2> err.log | Write only errors to a file |
cmd > out.log 2>&1 | Output and errors into the same file |
cmd 2>/dev/null | Throw errors away |
cmd | sudo tee file | Write to a root-owned file (tee -a appends) |
cmd | tee file | Show on screen and write to file |
cmd < file | Read input from a file instead of the keyboard, e.g. mysql db < dump.sql |
cmd <<EOF … EOF | “Here document”: feed the following lines as input (handy in scripts) |
cmd & | Run in the background, get the prompt back right away |
Chaining commands
| Syntax | Runs the second command… |
|---|---|
a ; b | always |
a && b | only if a succeeded |
a || b | only if a failed |
echo "$(hostname)" | inserts the output of a command |
sudo apt update && sudo apt upgrade -y only upgrades if the update worked. Every command returns an exit code: 0 = success, anything else = error. echo $? shows the last one.
Useful one-liners
Find text
grep -i "error" /var/log/syslog # lines containing "error", any case
grep -rn "listen" /etc/nginx/ # search all files in a folder, with line numbers
grep -v "^#" /etc/ssh/sshd_config | grep -v "^$" # config without comments and empty lines
Find files
find /var/log -name "*.log" -mtime -1 # .log files changed in the last 24h
find / -size +1G 2>/dev/null # files bigger than 1 GB
find /tmp -type f -mtime +30 -delete # delete files older than 30 days (test without -delete first!)
What fills my disk?
sudo du -xh --max-depth=1 / | sort -h # biggest folders on the root file system
sudo du -sh /var/log/* | sort -h | tail # biggest items in /var/log
Count, sort, filter
sudo ss -tn | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -rn | head
# -> which IPs have the most open TCP connections
Run a command for many files
find /srv/app -name "*.sh" | xargs chmod +x
More in xargs: run a command for many items.