Oct 21

The Linux command line is maligned and misrepresented as a confusing collection of old-world characters and clumsy techniques, reserved solely for those with chest-long beards. This preconception is nonsense. It isn’t difficult to use, it isn’t the sole reserve of experts and it shouldn’t be left as a last resort. There are many times when the command line is simply the easiest and quickest way to accomplish something. For example, typing ls to list a directory or cd to switch to another is simple and fast. Renaming files and folders by typing mv followed by the source name and new name is a breeze. And deletion is just as straightforward: simply enter rm.

Create a colourful custom command line today. Go on.

This tetrad of commands can look confusing because they’re only two letters long, but each is just an abbreviation: ‘ls’ is short for list, ‘cd’ for change directory, ‘mv’ for move and ‘rm’ for remove. To further minimise the amount of typing, the command line has an auto-complete feature activated by hitting [Tab] after entering the first few characters of your target filename. Doing things like this is far quicker than clicking on a file manager, finding the correct location and performing a point-and-click operation. Many people use the command line for only these commands.

But there’s a lot more to the shell than simple file management. Before the world was dominated by GUIs, mice and windows, people lived with the command line and turned the environments into a home from home. As a result, there are plenty of ways to make the command line more personal, easier to use and more efficient. It’s just a matter of knowing where to look.

Open up Bash

The specific command line used by nearly every mainstream Linux distribution is Bash. This is an acronym for Bourne Again Shell, which is itself a reference to one of the original shells, Bourne. Bash is the standard command line that greets you when you click on ‘Terminal’ in Ubuntu’s Accessories menu. It’s probably the easiest and most straightforward to use of all the command-line shells.

The standard Bash shell highlights folders in blue.

What isn’t so obvious is how Bash – and, indeed, any other command-line tool – can be configured. The answer lies hidden in mysterious ‘dot’ files, so called because any file on the Linux filesystem that starts with a full stop will be hidden from ordinary directory listing and File Manager views. You can reveal them by typing ls -a (list all). By default, Ubuntu’s configuration of Bash will display these files in blue in order to easily distinguish them from your standard filesystem, although this might not necessarily be the case with your chosen distribution.

Dot files exist for the sake of convenience rather than subterfuge. They have evolved to store configuration information, and there are so many of them that the average home directory is likely to have more of them than genuine files. There are hidden directories for both KDE and Gnome, with the latter spreading its options across several subdirectories. Almost every application you run on your Linux desktop will use a hidden dot file to save your preferences and its own configuration options.

Find hidden dot files

Bash uses several different files depending on what you want to configure. The principal file – and the one we’re most interested in here – is ‘.bashrc’. You might also see an assortment of other dot files related to Bash, including ‘.bash_profile’, ‘.bash_login’, ‘.bash_logout’ and ‘.bash_history’. Both the ‘rc’ file and the ‘_profile’ file are used to configure the command line for a whole session, with the difference between them being that the former is used when you launch Bash from your desktop while the latter comes into play if you choose to avoid GUIs completely and jump straight to the command line at login instead. Most of the time, the contents of one file point to the other.

Calling these dot files configuration files is technically inaccurate, because they’re really scripts rather than data files that are read into an application. Each line within the configuration file is executed in exactly the same way it would be had you typed it into the command prompt, which makes them more like set-up macros than configuration files. This is also the reason why you’ll find individual log-in and log-out variations. These are Bash scripts that are executed whenever you log in and log out from within Bash, which is useful if you switch users during a command line session. The only exception is ?‘.bash_history’, which is simply a transcript of everything that you’ve typed into Bash over a preconfigured number of lines.

Use nano to edit your distribution’s .bashrc file.

Most Linux distributions will have their own version of the ?‘.bashrc’ file, which they’ll use to set up system-specific parameters, such as whether the prompt uses colour, what the prompt actually consists of and the way in which your command completion is configured. The best way of finding out what a particular configuration file does is to take a look at it. You can do this in one of two ways: either by typing nano.bashr into the command line, or from your desktop through your favourite text editor. If you’re using Gnome, you’ll have to right-click within the file manager and then select ‘Show Hidden Files’ in order to see ‘.bashrc’.

Understand comments

The best thing about most of Bash’s configuration files is that they’re well documented. Within each section, you’ll find an area where each line begins with a ‘#’ symbol. This symbol tells the script interpreter to ignore the following text, which is why you’ll usually find some helpful instructions following it.

Even without any Bash knowledge, you should be able to decode the instructions used to build the default environment and make small changes more in tune with the way you work. A good example is enabling the coloured prompt. This is disabled by most distributions, but you should be able to find the line to activate it without too much difficulty. Look for the line ‘#force_color_prompt=yes’ and remove the ‘#’ to change the line from a comment to an active part of the script. If you now open a new terminal session, you should see that the colour of the prompt has changed.

You can enable your coloured prompt simply by removing a hash symbol.

The parts of the script that make the colour change happen are the two ‘if’ sections that follow the colour prompt line. If you’ve ever done any programming, you’ll recognise ‘if’. It’s the statement that will do one thing or another depending on the contents of a condition, which is the formula you’ll find within the square brackets. Logical programming elements like this help to make Bash scripts far more powerful than a group of single lines, and they’re a great way to get into programming if you’ve never seen anything like this before. You don’t even have to write a script – you can use logical statements such as ‘if’ directly on the command line.

If you wanted to prove to yourself that bashrc is just executed sequentially, for instance, you could copy and paste these ‘if’ sections directly into an active command-line session. The results would be identical to starting a new session to see a colourful prompt.

Customise the prompt

As you might have guessed from the lines hidden within the configuration file, one of its main uses is to change the appearance of the command prompt. This is the part that comes before the cursor, and on Ubuntu systems this simply states your user and machine name followed by the current directory location. But it needn’t be this way. People have expended hours perfecting the prompt, turning it into everything from a fortune cookie reader to an emoticon that tells you whether the previous command worked.

The prompt is configured through something called the PS1 variable, and you can find it defined at various locations within the bashrc file. For example, the colour prompt setting we changed earlier decides between a mono and colour version of the PS1 prompt. If you’ve enabled the colour setting, you can replace the $ symbol that appears at the end of the prompt by editing the last character in the line that follows the PS1 definition (in the line after ‘if [ “$colour_prompt” = yes ];’).

There’s a lot more to prompt modification than character replacement, and this comes from the use of special characters. Replace \$ with \t, for example, and you’ll get the current time at the end of your prompt. Switch this with \d and you’ll get the date. Other special characters that you can insert following the slash character include w for the current working directory, h for the name of your machine and u for the name of the current user.

Why not enable cowsay? It’s whimsical.

You can also run tools from the prompt by embedding commands within the ` symbols (called the back quote, or (properly, but confusingly given modern day terminology) the backslash). Two great examples include the fortune tool, which will output the kind of prophecy you typically find in a fortune cookie, or our favourite, cowsay, a tool that displays an ASCII-art cow with a bubble quote and variable mood setting. Either can be installed through the package manager, and you’ll then be able to add them to your own prompt. To add cowsay’s wisdom, for instance, change the prompt to: PS1=‘`cowsay -p “What are you going to do?”`\n\$’.

The ‘-p’ sets the cow’s mood as ‘paranoid’, but you can also choose dead (-d), greedy (-g) or tired (-t). If you’ve got some spare time over lunch, you could even make the choice of cow displayed dependent upon whether the previous command was successful.

Try advanced features

This leads us on to some of the more advanced features found within Bash. One of the most useful is the alias command. It’s already being used within the configuration file to quietly replace any occurrence of the grep command, with grep -colour adding colour to the command’s output whether you define it manually or not. You can use the same trick to modify other commands you might commonly use. You could add alias la=‘ls -a’ to the file so that typing la on the command line becomes a shortcut for the long list output we used earlier. Or you could string commands together, such as alias lh=‘ls -a |grep .’, which will pipe the output of the ‘ls -a’ command into grep, which will in turn filter out all files and folders that don’t contain a full stop.

Create a little code and you can build your own command line extensions.

You can even start programming. Any functions you define within bashrc can be accessed from the command line, and this is perfect for creating automatic archive managers, or making clever use of ordinary commands. Add the following to your configuration file:

function mkcd {
mkdir -p $1
cd $1
}

After launching a new terminal session, typing mkcd test will create a directory called test, and then ‘cd’ into it at the same time. All the ‘$1’ combination does is pass the first argument from your command to the mkcd function, which it uses as an argument for the mkdir command. Using $2 or $3 would interact with the second or third arguments instead.

Using this as the basis for other functions, combined with the various aspects of Bash we’ve just covered, opens your terminal usage up to limitless possibilities, and helps you to finally tame the command line.

Other shells

Free software is all about choice, so it should come as no surprise to learn that there are plenty of other interpretations of what a shell should be, and you’re free to replace Bash with any that takes your fancy. Just take a look at what’s in your distribution’s package manager and install one that you think is worthwhile. You’ll then be able to try it out by typing the name of its executable into Bash. Make it the default choice by typing usermod -s /path/to/shell username or editing the /etc/password configuration file.

Z-shell is a popular option, and it differs from Bash in two important ways. Firstly, there’s no decent default configuration. This means you have to step through an install wizard the first time you use it, and hand-edit the configuration files to add basics like a visible command prompt. But it’s often worth the effort, because Zsh could be considered easier to use than Bash. Tab completion, for example, is much better implemented. It can guess misspelt filenames, replace long strings of characters with the letters ‘xx’ and automatically fill in the arguments of some of the most common tools and utilities.

On the more technical side, another popular shell is C-shell. As its name implies, much of its syntax takes inspiration from the C programming language, although many other shells have now adopted similar ideas, especially with their scripts and condition statements. But it does have excellent job management facilities, and many scripts are still written using Csh.

Comments are closed.