Spend a lot of your day looking at a Bash command line? I do. Because of this, I try to be as efficient as possible when using Bash. In this article I will describe some of the bash features I commonly use to help me save time.
Repeat the last argument of your last command:
mkdir /path/to/exampledir
cd !$
Run your last command again:
!!
Reversed History Search
CTRL-R (start typing a command that would be in your Bash history)
Execute last command starting with…
!COMMAND (Example: !vim)
Print the last command that contained…
!string:p (Example:!ssh:p may return ssh root@192.168.1.1)
Execute last command that contained…
!?string (Example:!?passwd may expand to cat /etc/passwd)
Previous command substitution:
!command:s/search/replace/ (Example:!vim:s/passwd/shadow/ would replace vim /etc/passwd with vim /etc/shadow)
Return the exit status of your last command:
$?
Run a numbered command from your history
!NUMBER
Last but not least….Brace Expansion. This is best explained with some examples:
echo {five,six,seven,eight}
five six seven eight
echo happy{" birthday"," anniversary"}
happy birthday happy anniversary
echo {Mac,Cent}OS
MacOS CentOS
Are you asking yourself, “how is that useful?”. Here’s how:
cp /etc/httpd/conf/httpd.conf{,.bak}
cp /etc/httpd/conf/httpd.conf /etc/httpd/conf/httpd.conf.bak
rm -f /var/log/mail.log.{3,5,7,9}
rm -f /var/log/mail.log.3 /var/log/mail.log.5 /var/log/mail.log.7 /var/log/mail.log.9
Have any other useful Bash tricks? Post them up as comments!