Time-Saving Tricks on the Command Line

I remember the first time a friend of mine introduced me to Linux and showed me how I didn't need to type commands and path names fully—I could just start typing and use the Tab key to complete the rest. That was so cool. I think everybody loves Tab completion because it's something you use pretty much every minute you spend in the shell. Over time, I discovered many more shortcuts and time-saving tricks, many of which I have come to use almost as frequently as Tab completion.

In this article, I highlight a set of tricks for common situations that make a huge difference for me:

  • Working in screen sessions: core features that will get you a long way.

  • Editing the command line: moving around quickly and editing quickly.

  • Viewing files or man pages using less.

  • E-mailing yourself relevant log snippets or alerts triggered by events.

While reading the article, it would be best to have a terminal window open so you can try using the tips right away. All the tips should work in Linux, UNIX and similar systems without any configuration.

Working in Screen Sessions

Screen has been covered in Linux Journal before (see Resources), but to put it simply, screen lets you have multiple "windows" within a single terminal application. The best part is that you can detach and reattach to a running screen session at any time, so you can continue your previous work exactly where you left off. This is most useful when working on a remote server.

Luckily, you really don't need to master screen to benefit from it greatly. You already can enjoy its most useful benefits by using just a few key features, namely the following:

  • screen -R projectx: reattach to the screen session named "projectx" or create it fresh now.

  • Ctrl-a c: create a new window.

  • Ctrl-a n: switch to the next window.

  • Ctrl-a p: switch to the previous window.

  • Ctrl-a 0: switch to the first window; use Ctrl-a 1 for the second window, and so on.

  • Ctrl-a w: view the list of windows.

  • Ctrl-a d: detach from this screen session.

  • screen -ls: view the list of screen sessions.

Note: in the above list, "Ctrl-a c" means pressing the Ctrl and a keys at the same time, followed by c. Ctrl-a is called the command key, and all screen commands start with this key sequence.

Let me show all of these in the context of a realistic example: debugging a Django Web site on my remote hosting server, which usually involves the following activities:

  • Editing the configuration file.

  • Running some commands (performing Django operations).

  • Restarting the Web site.

  • Viewing the Web site logs.

Of course, I could do all these things one by one, but it's a lot more practical to have multiple windows open for each. I could use multiple real terminal windows, but reopening them every time I need to do this kind of work would be tedious and slow. Screen can make this much faster and easier.

Starting Screen:

Before you start screen, it's good to navigate to the directory where you expect to do most of your work first. This is because new windows within screen will all start in that directory. In my example, I first navigate to my Django project's directory, so that when I open new screen windows, the relevant files will be right there in front of me.

There are different ways of starting screen, but I recommend this one:


screen -R mysite

When you run this the first time, it creates a screen session named "mysite". Later you can use this same command to reconnect to this session again. (The -R flag stands for reattach.)

Creating Windows:

Now that I'm in screen, let's say I start editing the configuration of the Django Web site:


vim mysite/settings.py

Let's say I made some changes, and now I want to restart the site. I could exit vim or put it in the background in order to run the command to restart the site, but I anticipate I will need to make further changes right here. It's easier just to create a new window now, using the screen command Ctrl-a c.

It's easy to create another window every time you start doing something different from your current activity. This is especially useful when you need to change the directory between commands. For example, if you have script files in /some/long/path/scripts and log files in /other/long/path/logs, then instead of jumping between directories, just keep a separate window for each.

In this example, first I started looking at the configuration files. Next, I wanted to restart the Web site. Then I wanted to run some Django commands, and then I wanted to look at the logs. All these are activities I tend to do many times per debugging session, so it makes sense to create a separate window for each activity.

The cost of creating a new window is so small, you can do it without thinking. Don't interrupt your current activity; fire up another window with Ctrl-a c and rock on.

Switching between Windows:

The windows you create in screen are numbered starting from zero. You can switch to a window by its number—for example, jump to the first window with Ctrl-a 0, the second window with Ctrl-a 1 and so on. It's also very convenient to switch to the next and previous windows with Ctrl-a n and Ctrl-a p, respectively.

Listing Your Windows:

If you're starting to lose track of which window you are in, check the list of windows with Ctrl-a w or Ctrl-a ". The former shows the list of windows in the status line (at the bottom) of the screen, showing the current window marked with a *. The latter shows the list of windows in a more user-friendly format as a menu.

Detaching from and Reattaching to a Session:

The best time-saving feature of screen is reattaching to existing sessions. You can detach cleanly from the current screen session with Ctrl-a d. But you don't really need to. You could just as well simply close the terminal window.

The great thing about screen sessions is that whatever way you disconnected from them, you can reattach later. At the end of the day, you can shut down your local PC without closing a remote screen session and come back to it the next day by running the same command you used to start it, as in this example with screen -R mysite.

You might have multiple screen sessions running for different purposes. You can list them all with:


screen -ls

If you are disconnected from screen abruptly, sometimes it may think you are still in an attached state, which will prevent you from reattaching with the usual command screen -R label. In that case, you can append a -D flag to force detach from any existing connections—for example:


screen -R label -D

Learning More about Screen:

If you want to learn more, see the man page and the links in the Resources section. The built-in cheat sheet of shortcuts also comes handy, and you can view it with Ctrl-a ?.

I also should mention one of screen's competitor: tmux. I chose screen in this article because in my experience, it is more available in systems I cannot control. You can do everything I covered above with tmux as well. Use whichever is available in the remote system in which you find yourself.

Finally, you can get the most out of screen when working on a remote system—for example, over an SSH session. When working locally, it's probably more practical to use a terminal application with tabs. That's not exactly the same thing, but probably close enough.

Editing the Command Line

Many highly practical shortcuts can make you faster and more efficient on the command line in different ways:

  • Find and re-run or edit a long and complex command from the history.

  • Edit much more quickly than just using the backspace key and retyping text.

  • Move around much faster than just using the left- and right-arrow keys.

Finding a Command in the History:

If you want to repeat a command you executed recently, it may be easy enough just to press the up-arrow key a few times until you find it. If the command was more than only a few steps ago though, this becomes unwieldy. Very often, it's much more practical to use the Ctrl-r shortcut instead to find a specific command by a fragment.

To search for a command in the past, press Ctrl-r and start typing any fragment you remember from it. As you type, the most recent matching line will appear on the command line. This is an incremental search, which means you can keep typing or deleting letters, and the matched command will change dynamically.

Let's try this with an example. Say I ran these commands yesterday, which means they are still in my recent history but too far away simply to use the up arrow:


...
cd ~/dev/git/github/bashoneliners/
. ~/virtualenv/bashoneliners/bin/activate
./run.sh pip install --upgrade django
git push beta master:beta
git push release master:release
git status
...

Let's say I want to activate the virtualenv again. That's a hassle to type again, because I have to type at least a few characters at each path segment, even with Tab completion. Instead, it's a lot easier to press Ctrl-r and start typing "activate".

For a slightly more complex example, let's say I want to run a git push command again, but I don't remember exactly which one. So I press Ctrl-r and start typing "push". This will match the most recent command, but I actually want the one before that, and I don't remember a better fragment to type. The solution is to press Ctrl-r again, in the middle of my current search, as that jumps to the next matching command.

This is really extremely useful, saving not only the time of typing, but also often the time of thinking too. Imagine one of those long one-liners where you processed a text file through a long sequence of pipes with sed, awk, Perl and whatnot; or an rsync command with many flags, filters and exclusions; or complex loops using "for" and "while". You can bring those back to your command line quickly using Ctrl-r and some fragment you remember from them.

Here are a few other things to note:

  • The search is case-sensitive.

  • You can abort the search with Ctrl-c.

  • To edit the line before running it, press any of the arrow keys.

This trick can be even more useful if you pick up some new habits. For example, when referring to a path you use often, type the absolute path rather than a relative path. That way, the command will be reusable later from any directory.

Moving Around Quickly and Editing Quickly:

Basic editing on the command line involves moving around with the arrow keys and deleting characters with Backspace or Delete. When there are more than only a few characters to move or delete, using these basic keys is just too slow. You can do the same much faster by knowing just a handful of interesting shortcuts:

  • Ctrl-w: cut text backward until space.

  • Esc-Backspace: cut one word backward.

  • Esc-Delete: cut one word forward.

  • Ctrl-k: cut from current position until the end of the line.

  • Ctrl-y: paste the most recently cut text.

Not only is it faster to delete portions of a line chunk by chunk like this, but an added bonus is that text deleted this way is saved in a register so that you can paste it later if needed. Take, for example, the following sequence of commands:


git init --bare /path/to/repo.git
git remote add origin /path/to/repo.git

Notice that the second command uses the same path at the end. Instead of typing that path twice, you could copy and paste it from the first command, using this sequence of keystrokes:

  1. Press the up arrow to bring back the previous command.

  2. Press Ctrl-w to cut the path part: "/path/to/repo.git".

  3. Press Ctrl-c to cancel the current command.

  4. Type git remote add origin, and press Ctrl-y to paste the path.

Some of the editing shortcuts are more useful in combination with moving shortcuts:

  • Ctrl-a: jump to the beginning of the line.

  • Ctrl-e: jump to the end of the line.

  • Esc-b: jump one word backward.

  • Esc-f: jump one word forward.

Jumping to the beginning is very useful if you mistype the first words of a long command. You can jump to the beginning much faster than with the left-arrow key.

Jumping forward and backward is very practical when editing the middle part of a long command, such as the middle of long path segments.

______________________

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.

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState