Time-Saving Tricks on the Command Line

Putting It All Together:

A good starting point for learning these little tricks is to stop some old inefficient habits:

  • Don't clear the command line with the Backspace key. Use Ctrl-c instead.

  • Don't delete long arguments with the Backspace key. Use Ctrl-w instead.

  • Don't move to the beginning or the end of the line using the left- and right-arrow keys. Jump with Ctrl-a and Ctrl-e instead.

  • Don't move over long terms using the arrow keys. Jump over terms with Esc-b and Esc-f instead.

  • Don't press the up arrow 20 times to find a not-so-recent previous command. Jump to it directly with Ctrl-r instead.

  • Don't type anything twice on the same line. Copy it once with Ctrl-w, and reuse it many times with Ctrl-y instead.

Once you get the hang of it, you will start to see more and more situations where you can combine these shortcuts in interesting ways and minimize your typing.

Learning More about Command-Line Editing:

If you want to learn more, see the bash man page and search for "READLINE", "Commands for Moving" and "Commands for Changing Text".

Viewing Files or man Pages with less

The less command is a very handy tool for viewing files, and it's the default application for viewing man pages in many modern systems. It has many highly practical shortcuts that can make you faster and more efficient in different ways:

  • Searching forward and backward.

  • Moving around quickly.

  • Placing markers and jumping to markers.

Searching Forward and Backward:

You can search forward for some text by typing / followed by the pattern to search for. To search backward, use ? instead of /. The search pattern can be a basic regular expression. If your terminal supports it, the search results are highlighted with inverted foreground and background colors.

You can jump to the next result by pressing n, and to the previous result by pressing N. The direction of next and previous is relative to the direction of the search itself. That is, when searching forward with /, pressing n will move you forward in the file, and when searching backward with ?, pressing n will move you backward in the file.

If you use the vim editor, you should feel right at home, as these shortcuts work the same way as in vim.

Searching is case-sensitive by default, unless you specify the -i flag when starting less. When reading a file, you can toggle between case-sensitive and insensitive modes by typing -i.

Moving Around Quickly:

Here are a couple shortcuts to help you move around quickly:

  • g: jump to the beginning of the file.

  • G: jump to the end of the file.

  • space: move forward by one window.

  • b: move backward by one window.

  • d: move down by a half-window.

  • u: move up by a half-window.

Using Markers:

Markers are extremely useful in situations when you need to jump between two or more different parts within the same file repeatedly.

For example, let's say you are viewing a server log with initialization information near the beginning of the file and some errors somewhere in the middle. You need to switch between the two parts while trying to figure out what's going on, but using search repeatedly to find the relevant parts is very inconvenient.

A good solution is to place markers at the two locations so you can jump to them directly. Markers work similarly as in the vim editor: you can mark the current position by pressing m followed by a lowercase letter, and you can jump to a marker by pressing ' followed by the same letter. In this example, I would mark the initialization part with mi and the part with the error with me, so that I could jump to them easily with 'i and 'e. I chose the letters as the initials of what the locations represent, so I can remember them easily.

Learning More Shortcuts:

If you are interested in more, see the man page for the less command. The built-in cheat sheet of shortcuts also comes handy, and you can view it by pressing h.

E-mailing Yourself

When working on a remote server, getting data back to your PC can be inconvenient sometimes—for example, when your PC is NAT-ed and the server cannot connect to it directly with rsync or scp. A quick alternative might be sending data by e-mail instead.

Another good scenario for e-mailing yourself is to use alerts triggered by something you were waiting for, such as a crashed server coming back on-line or other particular system events.

E-mailing a Log Snippet:

Let's say you found the log of errors crashing your remote service, and you would like to copy it to your PC quickly. Let's further assume the relevant log spans multiple pages, so it would be inconvenient to copy and paste from the terminal window. Let's say you can extract the relevant part using a combination of the head, tail and grep commands. You could save the log snippet in a file and run rsync on your local PC to copy it, or you could just mail it to yourself by simply piping it to this command:


mailx -s 'error logs' me@example.com

Depending on your system, the mailx command might be different, but the parameters are probably the same: -s specifies the subject (optional), the remaining arguments are the destination e-mail addresses, and the standard input is used as the message body.

Triggering an E-mail Alert after a Long Task

When you run a long task, such as copying a large file, it can be annoying to wait and keep checking whether it has finished. It's better to arrange to trigger an e-mail to yourself when the copying is complete—for example:


the_long_task; date | mailx -s 'job done' me@example.com

That is, when the long task has completed, the e-mail command will run. In this example, the message body simply will be the output of the date command. In a real situation, you probably will want to use something more interesting and relevant as the message—for example ls -lh on the file that was copied or even multiple commands grouped together like this:


the_long_task; { df -h; tail some.log; } | \
    mailx -s 'job done' me@example.com

Triggering an E-mail Alert by Any Kind of Event:

Have you ever been in one of the following situations?

  • You are waiting for crashed serverX to come back on-line.

  • You are tailing a server log, waiting for a user to test your new evolution, which will trigger a particular entry in the log.

  • You are waiting for another team to deploy an updated .jar file.

Instead of staring at the screen or checking repeatedly whether the event you are waiting for has happened, you could use this kind of one-liner:


while :; do date; CONDITION && break; sleep 300; \
done; MAILME

This is essentially an infinite loop, with an appropriate CONDITION in the middle to exit the loop and, thus, trigger the e-mail command. Inside the loop, I print the date, just so that I can see the loop is alive, and sleep for five minutes (300 seconds) in each cycle to avoid overloading the machine I'm on.

CONDITION can be any shell command, and its exit code will determine whether the loop should exit. For the situations outlined above, you could write the CONDITION like this:

  • ping -c1 serverX: emit a single ping to serverX. If it responds, ping will exit with success, ending the loop.

  • grep pattern /path/to/log: search for the expected pattern in the log. If the pattern is found, grep will exit with success, ending the loop.

  • find /path/to/jar -newer /path/to/jar.marker: this assumes that before starting the infinite loop, you created a marker file like this: touch -r /path/to/jar /path/to/jar.marker in order to save a copy of the exact same timestamp as the .jar file you want to monitor. The find command will exit with success after the jar file has been updated.

In short, don't wait for a long-running task or some external event. Set up an infinite loop, and alert yourself by e-mail when there is something interesting to see.

Conclusion

All the tips in this article are standard features and should work in on Linux, UNIX and similar systems. I have barely scratched the surface here, highlighting the minimal set of features in each area that should provide the biggest bang for your buck. Once you get used to using them, these little tricks will make you a real ninja in the shell, jumping around and getting things done lightning fast with minimal typing.

Resources

Type man screen.

Type man bash, and search for "READLINE", "Commands for Moving" and "Commands for Changing Text".

Type man less.

Janos Gyerik's Talk on Time-Saving Tips on the Command Line: https://speakerdeck.com/janosgyerik/time-saving-tricks-on-the-command-line

"Power Sessions with Screen" by Adam Lazur, LJ, January 2013: http://www.linuxjournal.com/article/6340

"Status Messages in Screen" by Kyle Rankin, LJ, March 2011: http://www.linuxjournal.com/article/10950

"Transfer Your Terminal with Screen" (Video) by Shawn Powers: http://www.linuxjournal.com/video/transfer-your-terminal-screen

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Once I am done with the work,

sollen's picture

Once I am done with the work, I estimate I ll still have spent 33W Mining driving lamp less than the book value of the car, and will have a car that is reliable and dependable to show for it.

This is very interesting

LawrenceR's picture

This is very interesting article. It gives good ideas. http://norvascotc.com/

Better would be to type 'git

Mirosław Nagaś's picture

Better would be to type 'git remote add origin' and press Alt-. which will paste the last argument of the previous command.

I am impressed, I must say.

order food online's picture

I am impressed, I must say. Really rarely do I encounter a blog that’s both educative and entertaining, and let me tell you, you have hit the nail on the head. Your idea is outstanding; the issue is something that not enough people are speaking intelligently about. I am very happy that I stumbled across this in my search for something relating to this.

Real improvement

emzap79's picture

that's one of those articles I enjoy reading from the beginning untill the end (even if I haven't finished yet ^^). I think it contains some real good hints which will improve my working flow A LOT! The only thing I will keep doing as always other than described is key-combination ALT-f instead of Esc-b to jump one word backward within the terminal.

This is a matter of taste I guess and does not diminish the value of this article at all! Thank you for this!

Alternative for Command Line Editing

Howard's picture

As an alternative command line editor, you can use "set -o vi" and use familiar vi keybindings to edit your command line. I've been using this for years, and because we use vi/vim as our standard editors, it allows us to concentrate on only one command set, to make the job easier.

Reply to comment | Linux Journal

Your Porn Bookmarks is your favourite place to look for the 's picture

No matter if some one searches for his vital thing, therefore he/she wants to be available that in detail, therefore
that thing is maintained over here.

remarks

PePas's picture

Thanks for this article, always good to refresh skillsets.

I was curious what would happen on some of my systems with mailx; one said I needed an MTA installed, and another one made 2 suggestions on providing mailx: heirloom-mailx and mailutils
(that particular system already had mstmp that I use to just send emails). The Debian box just didn't know the command. I installed heirloom-mailx on one box, but then got the message that sendmail wasn't found, and a dead.letter was created.
In short, I'd recommend installing msmtp if mailx doesn't work.

Curious why you're not using the while loop the way it was intended:

while ! CONDITION; do date; sleep 300; done; MAILME

Don't forget: Escape-Dot adds last argument of previous command

Anonymous's picture

This seems to be little known!
Pressing Esc . repeats the last argument!
EG
ls path/to/my/dir
cd Esc .

Comment a line

xrat's picture

I use Esc . everyday. Another one is Esc #
It's a shortcut for ^A # ^M, so it puts a # at the start of the line and doesn't excute it. Still it shows up in the (Bash) history so one can re-access it later, edit it, remove the # and execute.

Use TMUX as an alternative to Screen

Dejan Lekic's picture

I used Screen for nearly a decade, and recently started using TMUX instead. It is IMHO superior application comparing to Screen. Check it out, you won't be disappointed!

I second TMUX as a superior

JonT's picture

I second TMUX as a superior alternative to Screen. It's on all my servers.

TMUX not Standard

Howard's picture

The problem is, TMUX is not "standard" on most Linux systems, and trying to get it installed in a data center full of servers is practically impossible. This is why I concentrate on the "standard" applications I can usually count on.

tmux needs public awareness

stampeder's picture

With enough public acknowledgement of how much better it is than screen, tmux will take its place in most distros where it belongs.

Nice

zb's picture

I wish I had seen this a few years ago. Even with experience on the command line there were a number of interesting tips which I will be using in future.

My best tip for screen is to use it for irc. I keep a permanent session going on an always on server and can log in and attach the screen and see what has been going on while I was away.

Thanks.

Nice

Monomon's picture

I recently discovered screen at work (and a lot of other command-line goodies) and it's been a great learning.
Thanks for the article. Of course one could look up all this, but it is good to be reminded and also shown possible workflows using the tools.

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix