Wednesday 17 January 2018

LPIC-1: The Bash Shell and Commands and sequences

LPIC-1: The Bash Shell, Commands and sequences, LPI Guides, LPI Tutorials and Materials

1. The Bash Shell


The bash shell is one of several shells available for Linux. It is also called the Bourne-again shell, after Stephen Bourne, the creator of an earlier shell (/bin/sh). Bash is substantially compatible with sh, but it provides many improvements in both function and programming capability. It incorporates features from the Korn shell (ksh) and C shell (csh), and is intended to be a POSIX-compliant shell.

Unless otherwise noted, the examples in this tutorial use Fedora 22, with a 4.0.4 kernel. Your results on other systems may differ.

Prerequisites

To get the most from the tutorials in this series, you should have a basic knowledge of Linux and a working Linux system on which you can practice the commands covered in this tutorial. Sometimes different versions of a program will format output differently, so your results may not always look exactly like the listings and figures shown here.

Before we delve deeper into bash, recall that a shell is a program that accepts and executes commands. It also supports programming constructs, allowing complex commands to be built from smaller parts. These complex commands, or scripts, can be saved as files to become new commands in their own right. Indeed, many commands on a typical Linux system are scripts.

Shells have some builtin commands, such as cd, break, and exec. Other commands are external.

Shells also use three standard I/O streams:

◈ stdin is the standard input stream, which provides input to commands.
◈ stdout is the standard output stream, which displays output from commands.
◈ stderr is the standard error stream, which displays error output from commands.

Input streams provide input to programs, usually from terminal keystrokes. Output streams print text characters, usually to the terminal. The terminal was originally an ASCII typewriter or display terminal, but it is now more often a window on a graphical desktop.

If you are using a Linux system without a graphical desktop, or if you open a terminal window on a graphical desktop, you will be greeted by a prompt, perhaps like one of the three shown in Listing 1.

Listing 1. Some typical user prompts

[ian@atticf20 ~]$
jenni@atticf20:data
$

Notice that these three prompts are all from my test system atticf20, but for different users. The first two are bash prompts and both show the logged in user, system name and current working directory. The third is the default prompt on my system for a ksh shell. Different distributions and different shells default to different prompts, so don’t panic if your distribution looks different. We'll cover how to change your prompt string in another tutorial in this series.

If you log in as the root user (or superuser), your prompt may look like one of those shown in Listing 2.

Listing 2. Superuser, or root, prompt examples

[root@atticf20 ~]#
atticf20:~#

The root user has considerable power, so use it with caution. When you have root privileges, most prompts include a trailing pound sign (#). Ordinary user privileges are usually delineated by a different character, commonly a dollar sign ($). Your actual prompt may look different than the examples in this tutorial. Your prompt may include your user name, hostname, current directory, date, or time that the prompt was printed, and so on.

Note: Some systems, such as Debian and Debian-based distributions such as Ubuntu, do not allow root login and require all privileged (root) commands to be executed using the sudo command. In this case, your prompt will not change, but you will know that you have to use sudo to execute commands that an ordinary user does not have the power to execute.

These tutorials include code examples that are cut and pasted from real Linux systems using the default prompts for those systems. Our root prompts have a trailing #, so you can distinguish them from ordinary user prompts, which have a trailing $. This convention is consistent with many books on the subject. If something doesn't appear to work for you, check the prompt in the example.

2. Commands and sequences


So now that you have a prompt, let's look at what you can do with it. The shell's main function is to interpret your commands so you can interact with your Linux system. On Linux (and UNIX®) systems, commands have a command name, and then options and parameters. Some commands have neither options nor parameters, and some have one but not the other.

If a line contains a # character, then all remaining characters on the line are ignored. So a # character may indicate a comment as well as a root prompt. Which it is should be evident from the context.

Echo

The echo command prints (or echos) its arguments to the terminal as shown in Listing 3.

Listing 3. Echo examples

[ian@atticf20 ~]$ echo Word
Word
[ian@atticf20 ~]$ echo A phrase
A phrase
[ian@atticf20 ~]$ echo Where     are   my   spaces?
Where are my spaces?
[ian@atticf20 ~]$ echo "Here     are   my   spaces." # plus comment
Here     are   my   spaces.

In the third example of Listing 3, all the extra spaces were compressed down to single spaces in the output. To avoid this, you need to quote strings, using either double quotes (") or single quotes ('). Bash uses white space, such as blanks, tabs, and new line characters, to separate your input line into tokens, which are then passed to your command. Quoting strings preserves additional white space and makes the whole string a single token. In the example above, each token after the command name is a parameter, so we have respectively 1, 2, 4, and 1 parameters.

The echo command has a couple of options. Normally, echo will append a trailing new line character to the output. Use the -n option to suppress this. Use the -e option to enable certain backslash escaped characters to have special meaning. Some of these are shown in Table 1.

Table 1. Echo and escaped characters

Escape sequence Function 
\a Alert (bell)
\b  Backspace 
\c  Suppress trailing newline (same function as -n option) 
\f  Form feed (clear the screen on a video display) 
\n  New line 
\r  Carriage return 
\t  Horizontal tab 

Escapes and line continuation

There is a small problem with using backslashes in bash. When the backslash character (\) is not quoted, it serves as an escape to signal bash itself to preserve the literal meaning of the following character. This is necessary for special shell metacharacters, which we'll cover in a moment. There is one exception to this rule: a backslash followed by a newline causes bash to swallow both characters and treat the sequence as a line continuation request. This can be handy to break long lines, particularly in shell scripts.

For the sequences described above to be properly handled by the echo command or one of the many other commands that use similarly escaped control characters, you must include the escape sequences in quotes, or as part of a quoted string, unless you use a second backslash to have the shell preserve one for the command. Listing 4 shows some examples of the various uses of \.

Listing 4. More echo examples

[ian@atticf20 ~]$ echo -e "No new line\c"
No new line[ian@atticf20 ~]$ echo "A line with a typed
> return"
A line with a typed
return
[ian@atticf20 ~]$ echo -e "A line with an escaped\nreturn"
A line with an escaped
return
[ian@atticf20 ~]$ echo "A line with an escaped\nreturn but no -e option"
A line with an escaped\nreturn but no -e option
[ian@atticf20 ~]$ echo -e Doubly escaped\\n\\tmetacharacters
Doubly escaped
    metacharacters
[ian@atticf20 ~]$ echo Backslash \
> followed by newline \
> serves as line continuation.
Backslash followed by newline serves as line continuation.

Note that bash displays a special prompt (>) when you type a line with unmatched quotes. Your input string continues onto a second line and includes the new line character.

Bash shell metacharacters and control operators

Bash has several metacharacters, which when not quoted, also serve to divide input into words. Besides a blank, these are:

◈ |
◈ &
◈ ;
◈ (
◈ )
◈ <
◈ >

We will discuss some of these in more detail in other parts of this tutorial. For now, note that if you want to include a metacharacter as part of your text, it must be either quoted or escaped using a backslash (\) as shown in Listing 4.

The new line and certain metacharacters or pairs of metacharacters also serve as control operators. These are:

◈ ||
◈ &&
◈ &
◈ ;
◈ ;;
◈ |
◈ (
◈ )

Some of these control operators allow you to create sequences or lists of commands.

The simplest command sequence is just two commands separated by a semicolon (;). Each command is executed in sequence. In any programmable environment, commands return an indication of success or failure; Linux commands usually return a zero value for success and a non-zero value in the event of failure. You can introduce some conditional processing into your list using the && and || control operators. If you separate two commands with the control operator &&, then the second is executed if, and only if, the first returns an exit value of zero. If you separate the commands with ||, then the second one is executed only if the first one returns a non-zero exit code. Listing 5 shows some command sequences using the echo command. These aren't very exciting since echo returns 0, but you will see more examples later when we have a few more commands to use.

Listing 5. Command sequences

[ian@atticf20 ~]$ echo line 1;echo line 2; echo line 3
line 1
line 2
line 3
[ian@atticf20 ~]$ echo line 1&&echo line 2&&echo line 3
line 1
line 2
line 3
[ian@atticf20 ~]$ echo line 1||echo line 2; echo line 3
line 1
line 3

Exit

You can terminate a shell using the exit command. You may optionally give an exit code as a parameter. If you are running your shell in a terminal window on a graphical desktop, your window will close. Similarly, if you have connected to a remote system using ssh or telnet (for example), your connection will end. In the bash shell, you can also hold the Ctrl key and press the d key to exit.

Let's look at another control operator. If you enclose a command or a command list in parentheses, then the command or sequence is executed in a sub shell, so the exit command exits the sub shell rather than exiting the shell you are working in. Listing 6 shows a simple example in conjunction with && and || and two different exit codes.

Listing 6. Subshells and sequences

[ian@atticf20 ~]$ (echo In subshell; exit 0) && echo OK || echo Bad exit
In subshell
OK
[ian@atticf20 ~]$  (echo In subshell; exit 4) && echo OK || echo Bad exit
In subshell
Bad exit

Related Posts

0 comments:

Post a Comment