Skip to main content Link Menu Expand (external link) Document Search Copy Copied

Bash

Output in columns

ls -l | column -t

Avoid duplicate proces

pgrep certbot_watch >/dev/null || certbot_watch

Enable bash history timestamp

echo 'HISTTIMEFORMAT="%F %T "' >> ~/.bashrc

Every bash script

  • e -> exit on error
  • u -> exit on unset variable referenced
  • x -> show commands / activate debug out
#!/bin/bash
set -eu -o pipefail
set +x

Sort files in directory by size

ls -lhS

Sort directories by size

du -sh -- *  | sort -rh  # Files and directories, or
du -sh -- */ | sort -rh  # Directories only

Generate a password

tr -dc '[:alnum:]' </dev/urandom | head -c 12; echo

Add it to .bash_aliases:

alias genpw="tr -cd '[:alnum:]' < /dev/urandom | fold -w30 | head -n1"

Add my public ssh key

mkdir -p .ssh && echo "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMJZhBxjBZgaU5JQWaS2smXC9IFS46jR5jVdDYHyq8DS" >> .ssh/authorized_keys && chmod 600 .ssh/authorized_keys

Reset machine id

rm -f /etc/machine-id /var/lib/dbus/machine-id && dbus-uuidgen --ensure=/etc/machine-id && dbus-uuidgen --ensure

Read input in a script

echo "Enter something:
read username
echo "$username"

Bash for loop

for i in {1..5}; do COMMAND-HERE; done

or

for i in {1..5}; do COMMAND-HERE "$i"; done
for i in {1..5}; do echo "Hi, $i"; done

Bash for loop over lines in a file

while read db; do  echo $db; done < /tmp/dbnames.txt

Bash history

To immediately persist commands to your ~/.bash_history file and add a timestamp add this to ~/.bashrc: More info: here

HISTSIZE=11000
HISTFILESIZE=11000
HISTTIMEFORMAT="%F %T "
PROMPT_COMMAND='history -a'

History without line numbers

history -w /dev/stdout

Convert heif/heic to jpg

apt-get install libheif-examples`
for file in *.heic; do heif-convert "$file" "heic/${file/%.heic/.jpg}"; done

Cleanup Systemd journal

bash journalctl --vacuum-time=1d

Yesterday

YESTERDAY=`date -d "yesterday 13:00" '+%Y-%m-%d'`

SWAPPINESS

echo 'vm.swappiness = 15' >> /etc/sysctl.conf

or

sysctl vm.swappiness=15

SYSADMIN USER WITH SUDO

adduser sysadmin --disabled-password --ingroup sudo && echo 'sysadmin ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers

Email IP address with cron

25 20 * * *  /usr/bin/curl ifconfig.me | /usr/bin/mail -aFrom:hostname@you.nl -s "thuis ip" thuis@you.com

Check for IO WAIT

iostat 1 10
or
for x in `seq 1 1 30`; do ps -eo state,pid,cmd | grep "^D"; echo "-"; sleep 2; done

delete some file

shred -n 3 -z -u /root/github.txt

Create a password

echo -n "Enter Password: " && head -1 </dev/stdin | tr -d '\n' | sha256sum | cut -d" " -f1

Crazy way to set file permissions

#!/bin/sh
while f=$(inotifywait -e create --format "%f" /var/www/company/htdocs/ ) ; do
        chmod 664 '/var/www/company/htdocs/'$f
done

SCP over IPv6

scp -6 some_linux_binary  root@\[2a01:4f9:c010:9755::1\]:/root/

Run commands parallel

parallel --tag --linebuffer "ssh {} -- 'uptime'" ::: server-{1,2,3,4}