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:

StreamNumberDefault
stdin (input)0keyboard
stdout (output)1screen
stderr (errors)2screen

Pipes and redirects

SyntaxDoes
a | bOutput of a becomes input of b
cmd > fileWrite output to file (overwrites)
cmd >> fileAppend output to file
cmd 2> err.logWrite only errors to a file
cmd > out.log 2>&1Output and errors into the same file
cmd 2>/dev/nullThrow errors away
cmd | sudo tee fileWrite to a root-owned file (tee -a appends)
cmd | tee fileShow on screen and write to file
cmd < fileRead 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

SyntaxRuns the second command…
a ; balways
a && bonly if a succeeded
a || bonly 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.

§ home
~/knubertus/home/
1,1 Top