Examples of useful bash one-liners
Useful bash One-liners can improve your efficiency and make your work more enjoyable. Below is a collection of helpful bash one-liners.
Overview
- Run a command against multiple targets
- Find a directory that contains keyword
- Find all files modified in the last week
- Find your external IP with curl
- Find your external IP with dig
- Tcpdump with timestamp in file name
- Delete dynamic and static arp for /24 subnet
- Custom watch function
- Tail file until keyword
- Log SSH session
- Function to print columns
- List open files (-n skips dns resolution)
- Do not save command history of current session
- Copy files with progress indicator
- Check if file exists
- Add remote host public key to known hosts
- Highlight matching words
Run a command against multiple targets in a single line
1 |
for var in file1 file2;do cat $var;done |
Find a directory that contains keyword
1 |
find ./ -name *keyword* |
Find all files modified in the last week
1 |
find ./ -mtime -7 |
Find your external IP with curl
1 |
curl l2.io/ip |
Find your external IP with dig
1 |
dig +short myip.opendns.com @resolver1.opendns.com |
Tcpdump with timestamp in file name
1 |
date +'%Y-%m-%d_%H_%M-%Z' | xargs -I {} bash -c "sudo tcpdump -nq -s 0 -i eth0 -w ./tcpdump-{}.pcap" |
Delete dynamic and static arp for /24 subnet
1 |
for i in {1..254}; do arp -d 10.0.0.$i; done |
Custom watch function (ctrl+z SIGINT to stop)
Add function to current session or to ~/.bashrc
:
1 |
watch () { interrupted=false; trap "interrupted=true" INT; while ! $interrupted; do $*; sleep 1 || interrupted=true; done;} |
Use function:
1 |
watch grep alert /var/log/syslog |
Tail file until keyword
1 |
tail -f ./file.log | sed '/^Alert Found$/q' |
Log SSH session
1 |
ssh -l user host | tee -a ./file.txt |
Function to print columns (shortcut to … | awk ‘{print $4, $9}’)
Add function to current session or to ~/.bashrc
:
1 |
col() { awk '{print |
Use function:
1 |
ls -l | col 4 9 |
List open files (-n skips dns resolution)
1 |
lsof -n |
Do not save command history of current session
1 |
HISTFILE= |
Copy files with progress indicator
1 |
rsync --progress largefile.tar.gz other/location/ |
Check if file exists
1 |
if [ -f file.exists.txt ] ; then echo "yes" ; else echo "no" ; fi |
Add remote host public key to known hosts
1 |
ssh-keyscan remote_server >>~/.ssh/known_hosts |
1 |
$(echo $* | sed -e 's/ /,$/g')'}'; } |
Highlight matching words with grep but see all others
1 |
cat filename | grep --color -E 'FAIL|$' |