Here’s a few bash commands tricks I wished I’d been shown when I first picked up the shell. Please share any additional favorites you have.

Repeat the last command with sudo

How often do you type…

yum install long-list packages-devel

Only to be told…

You need to be root to perform this command.

Execute the following to install your packages…

sudo !!

The !! points to the previous command executed in the shell.

Save a readonly file in vi/vim

How many times have you opened a file in vi/vim, made lots of changes, only to be told it’s read-only when you attempt to save? Enter this in command mode to get around this…

:w !sudo tee

There’s a good explanation of this here.

alias

It can be time-consuming to search through your command history. Setup an alias instead.

alias shortcut="cmd -with=1 --lots=2 --of=3 -options=4 | piped -a -b -c"

The cmd with lots of options can now be executed as…

shortcut

Much simpler! Add these to your .bash_profile file to make them available permanently.

Clear your terminal window

I used to use clear for this. But this just shimmies everything upwards. Use..

reset

To actually clear the terminal screen.

Display output to a screen and save to a file

For a long time I was copying and pasting terminal output to save into text files. Then I discovered tee. Do this instead…

ls -lh | tee output.txt

Command-line calculator

For simple calculations on the command-line you can use bc.

echo "2 * 2" | bc

Outputs…

4