Linux tricks, one-liners & shell magic

#!/bin/vpp.dk

Community Linux tricks, one-liners & shell scripts — searchable & formatted.

Category: file-management — 5 trick(s)

+ Add a New Trick

Before editing a config, make a dated backup with a one-liner. The $(date) sub-shell appends the current timestamp.
bash
$ cp nginx.conf nginx.conf.$(date +%Y%m%d_%H%M%S).bak # Backup and keep last 5 only: cp important.conf important.conf.$(date +%Y%m%d).bak ls -t important.conf.*.bak | tail -n +6 | xargs rm -f
Delete this trick? This cannot be undone.
Stream new lines appended to a log file, useful for monitoring deployments or service output.
bash
$ tail -f /var/log/syslog # Follow multiple files at once: tail -f /var/log/nginx/access.log /var/log/nginx/error.log
Delete this trick? This cannot be undone.
Use grep to search through all files in a directory tree for a pattern, showing filenames and line numbers.
bash
$ grep -rn 'search_term' /path/to/dir/ # Case-insensitive, show 2 lines of context: grep -rin -C2 'error' /var/log/
Delete this trick? This cannot be undone.
A universal extract function you can add to ~/.bashrc — handles tar.gz, zip, bz2, 7z and more.
bash
$ extract() { case "$1" in *.tar.bz2) tar xjf "$1" ;; *.tar.gz) tar xzf "$1" ;; *.tar.xz) tar xJf "$1" ;; *.zip) unzip "$1" ;; *.7z) 7z x "$1" ;; *.gz) gunzip "$1" ;; *) echo "Unknown format: $1" ;; esac } # Usage: extract archive.tar.gz
Delete this trick? This cannot be undone.
Use sed with find to do a batch search-and-replace across many files at once.
bash
$ # Replace 'foo' with 'bar' in all .conf files: find /etc -name '*.conf' -exec sed -i 's/foo/bar/g' {} + # Preview changes first (dry-run): grep -rl 'foo' /etc/*.conf
Delete this trick? This cannot be undone.