Unix How To: Repeating Commands in Bash

Making use of previously entered commands can help you remember the location of files previously edited, canremove the need to re-enter long path names and can save you a lot of typing mistakes. Wtether you page back through your history with repetitions of up arrow presses or reuse commands by typing an exclamation point followed by the first few letters of the previously entered command, you can work faster and feel less annoyed by these useful time saving features of the Unix shell.

Bash, however, has a feature called "history mode" that takes your reuse of previously entered commands to new heights. You enter history mode by typing ^r (hold control key and press the letter "r"). You will see something like this:

(reverse-i-search)`':

At this point, you type some part of the command you want to reuse. It doesn't have to be the first few letters either. If you recently edited your samba configuration file, try "smb" or "conf" to fetch the line from your history. The history feature will locate the most recent command in which that string was used. If the command found is more recent than the one you're looking for, just type ^r again. Repeat pressing ^r as needed.

Once you find the command you're looking for, just press enter, just as you would is you were using the up arrow trick. Type ^c if you want to abandon the process altogether.

If you want to repeat some part of a previous command, you can always up arrow back to a command and then backspace over the parts you don't want to repeat. If you want to reuse just the last part of a command -- say you recently edited a file and now you want to page through it to verify that you change the proper lines, you can reuse just the last argument more easily using the !$ trick. !$ represents the final (rightmost) string in the previously entered command. So, if you just edited /usr/local/etc/smb.conf, you can page through the file with "more !$". If you create a directory named /usr/local/scripts/bin, you can go to that directory by typing "cd !$".

Other useful bash shortcuts include the following:

^a	Return to the start of the command you're typing
^e	Go to the end of the command you're typing
^u	Cut everything before the cursor to a special clipboard
^k	Cut everything after the cursor to a special clipboard
^y	Paste from the special clipboard that Ctrl + u and Ctrl + k save their data to
^t	Swap the two characters before the cursor (you can actually use this to transport a character from the left to the right, try it!)
^w	Delete the word / argument left of the cursor
^l	Clear the screen

With all the time you'll save, maybe you can get an early start on your holiday shopping!

Top 10 Hot Internet of Things Startups
Join the discussion
Be the first to comment on this article. Our Commenting Policies