Useful Bash One-liners
Below is a collection of useful Bash one-liners that we have come across and use semi-often (or at least often enough to not want to lose them). Honestly we mostly made this just in case we need them again and have lost them elsewhere, but hopefully they end up helping some of you as well!
Because theme reasons, only Bailey is listed as an author, but Ryan, Rob, and James also contribute to this list.
Recursively search all files in current directory, printing file name, line number, and match line:
grep -rnw ./ -e '$search_for'
Generate a random number between 1 and 10:
grep -m1 -ao '[0-9]' /dev/urandom | sed s/0/10/ | head -n1
Copy a file/folder with visible progress and checksum confirmation:
rsync -avz --progress $from $to
Send a packet over TCP or UDP on a specific port
echo "Message" > /dev/udp/$ip/$port echo "Message" > /dev/tcp/$ip/$port
List all zombie process ID’s:
ps aux | awk '{if ($8=="Z") { print $2 }}'
Get the name and parent of those processes:
pstree -p -s `ps aux | awk '{if ($8=="Z") { print $2 }}'`
Paste the current contents of the buffer:
xsel --clipboard --output
Print each line of a script as it runs:
bash -x $script
Repeat previous command with sudo privileges:
sudo !!
Breakdown of init systems:
Init Manager | systemd | OpenRC | SysV |
List run level services | systemctl list-units | rc-update show | ls /etc/rc*.d |
List all scripts | systemctl list-unit-files –type=service | rc-update -v show | service –status-all (or ls /etc/rc*.d or install sysv-rc-conf) |
Basic service management | systemctl (start|stop|status) $service | rc-service $service (start|stop|status) | service $service (start|stop|status) |
Add/remove service to start at boot | systemctl (enable|disable) $service | rc-service (add|del) $service (boot|default) | Make sure the service file is in /etc/init.d, then run update-rc.d $service defaults |
Here I would like to plug our article about cloning via dd, SSH, and gzip. It has a few useful commands that end up being extremely useful under the right circumstances. Here’s the link to that: