Bash Cheatsheet

List directories by size

du -smch * | sort -h | tail

Find

  • ..with a certain checksum... find ./ -type f -exec md5sum {} + | grep '^checksum' | cut -d '/' -f2
  • ...with a certain checksum and delete find ./ -type f -exec md5sum {} + | grep '^checksum' | cut -d '/' -f2 | xargs rm
  • ... files of zero size find ./ -type f -size 0
  • ...and delete find ./ -type f -size 0 -delete
  • ... directories of zero size find ./ -type d -empty

    Sample Script

    !/bin/bash

Last exit code

echo $?

Asking a user a question

echo -n "WHat is your name"

read -e NAME

echo "Your name is $NAME"

if [ $NAME = "php" ]
then
    php -i
fi

http://wiki.bash-hackers.org/howto/conffile

 Loop through directories

for d in */ ; do
        echo "$d"
done

Run a command 10 times

for ((n=0;n<10;n++)); do some_command; done

Variables

foldername=$(date +%Y%m%d)

Get a date variable

check=$(date +"%Y-%m-%d-%H:%M:%S")

Sed

Note mac sed is not the same as Linux - install gnu-sed with Brw

sed -i "s/pattern/replace/" filename

if using mac

gsed -i "s/pattern/replace/" filename

Installing Brew

brew install gnu-sed

brew install wget

Links

Setting colour of root prompt

edit /root/.bashrc

add:

PS1='\[\e[1;31m\][\u@\h \W]\$\[\e[0m\] '

https://wiki.archlinux.org/index.php/Color_Bash_Prompt