Stupid BASH Tricks

Posted on January 13th, 2009


Tired of your bland old BASH shell? sick of typing in lines and lines of cryptic commands? Arch Linux’s “pacman” still confusing you with it’s less than intuitive command switches? Fear not, true believers…for I come to you bearing gifts of Stupid BASH Tricks!

One thing I hate, is when ls doesn’t display things in colour, so I can’t tell what’s a file and what’s a directory. Soooo….Stupid BASH Trick #1 will rectify that little problem:

alias ls=”ls –color=always” && echo “alias ls=”ls –color=always”” >> ~/.bashrc

This little trick tells BASH, “every time the user types ‘ls’, they ACTUALLY mean ‘ls –colour=”always”‘. Also, the part after the “&&” puts that in a preference file that bash can access within your home folder so that parameter is active every time you log in. In fact, after all the little tricks I show you, I’ll add that, just so you get in the habit of typing it. I find this one particularly useful on Arch Linux installations, because I can never seem to remember how to search for packages. so I just did ‘alias pacman-search=”pacman -Ss”‘ and ‘alias pacman-install=”pacman -Sy”‘ for good measure.

Stupid BASH trick #2 also helps add a splash of colour to what is usually a colourless environment…only this adds it to the bash prompt itself.

PS1=”\[\033[1;34m\][\u@\h:\w]$\[\033[0m\] “

This takesĀ  your run-of-the-mill “[user@hostname:/somefolder]$ prompt, and gives it a splash of bold, tasteful, blue instead of bland, black text that can be indistinguishable from the morass of monospaced text crowding your terminal window. You can change this up however you like, and there are at least a dozen colours you can use. For more info on THAT though, check this handy little guide.

My next trick is something I used a lot back in my last job to suss out IPs responsible for causing DoS attacks on servers.

netstat -ntu | awk ‘{print $5}’ | cut -d: -f1 | sort | uniq -c | sort -n

Okay, Okay….maybe that one was a bit of a mouthful…but trust me, it’s VERY useful. It gives you a sorted list of unique IPs that are currently connected to the system you are logged into, and how many concurrent connections each IP has. Don’t wanna type all that? throw it in an alias, like I showed you with that first little trick…maybe something like alias doscheck=”netstat -ntu | awk ‘{print $5}’ | cut -d: -f1 | sort | uniq -c | sort -n”. and you could even maybe add a tail in there somewhere, so you only get the “worst offenders” out of the list.