Home » , » Commanding the Shell

Commanding the Shell

Written By Sajib Barua on Saturday, August 18, 2012 | 11:41 PM

previous The KDE Desktop

Sometimes, things just don’t work. What do you do if the GUI desktop stops responding to your mouse clicks? What if the GUI doesn’t start at all? You can still tell your Linux system what to do, but you have to do it by typing commands into a text screen. In these situations, you work with the shell — the Linux command interpreter. This chapter introduces the bash shell, the default shell in most Linux distributions.

After you figure out how to work with the shell, you may even begin to like the simplicity and power of the Linux commands. And then, even if you’re a GUI aficionado, someday soon you may find yourself firing up a terminal window and making the system sing and dance with two- or three-letter commands strung together by strange punctuation characters. (Hey, I can dream, can’t I?)
Opening Terminal Windows and Virtual Consoles
First things first. If you’re working in a GUI desktop, such as GNOME or KDE, where do you type commands for the shell? Good question.
The easiest way to get to the shell is to open a terminal (also called console) window. The GNOME and KDE GUIs in most distributions include an icon (or a Main Menu option) to open a terminal window. Click that icon or choose the menu option to get a terminal window. If you don’t see such an icon in GNOME, choose Applications»Accessories»Terminal. Now you can type commands to your heart’s content.
If, for some reason, the GUI seems to be hung (you click and type but nothing happens), you can turn to the virtual consoles. (The physical console is the monitor-and-keyboard combination.) The idea of virtual consoles is to give you the ability to switch between several text consoles even though you have only one physical console. Whether you’re running a GUI or not, you can then use different text consoles to type different commands.
To get to the first virtual console from the GNOME or KDE desktop, press Ctrl+Alt+F1. Press Ctrl+Alt+F2 for the second virtual console, and so on. Each of these virtual consoles is a text screen where you can log in and type Linux commands to perform various tasks. When you’re finished, type exit to log out.
You can use up to six virtual consoles. In most distributions, the seventh one is used for the GUI desktop. To get back to the GUI desktop, press Ctrl+Alt+F7.
Using the bash Shell
If you’ve used MS-DOS, you may be familiar with COMMAND.COM, the DOS command interpreter. That program displays the infamous C:\> prompt. In Windows, you can see this prompt if you open a command window. (To open a command window in Microsoft Windows, choose Start➪Run, type command in the text box, and then click OK.)
Linux comes with a command interpreter that resembles COMMAND.COM in DOS, but it can do a whole lot more. The Linux command interpreter is called a shell.
The default shell in many Linux distributions is bash. When you open a terminal window or log in at a text console, the bash shell is what prompts you for commands. Then, when you type a command, the shell executes your command.
Just as there are multiple GUIs (GNOME or KDE) for Linux, you have a choice of shells besides bash. For example, some people prefer the C shell. You can easily change your default shell by using the chsh command.
In addition to the standard Linux commands, bash can execute any computer program. So you can type the name of an application (the name is usually more cryptic than what you see in GNOME or KDE menus) at the shell prompt, and the shell starts that application.
Understanding the syntax of shell commands
Because a shell interprets what you type, knowing how the shell processes the text you enter is important. All shell commands have the following general format. (Some commands have no options.)
command [option1] [option2] . . . [optionN]
Issuing such a command is commonly referred to as a command line. On a command line, you enter a command, followed by zero or more options (or arguments). These strings of options — the command-line options (or command-line arguments) — modify the way the command works so that you can get it to do specific tasks.
The shell uses a blank space or a tab to distinguish between the command and options. This means you must use a space or a tab to separate the command from the options and the options from one another.
If an option contains spaces, you put that option inside quotation marks. For example, to search for my name in the password file, I enter the following grep command (grep is used for searching for text in files):
grep “Emmett Dulaney” /etc/passwd
When grep prints the line with my name, it looks like this:
edulaney:x:1000:100:Emmett Dulaney:/home/edulaney:/bin/bash
If you create a user account with your username, type the grep command with your username as an argument to look for that username in the /etc/passwd file.
In the output from the grep command, you can see the name of the shell (/bin/bash) following the last colon (:). Because the bash shell is an executable file, it resides in the /bin directory; you must provide the full path to it.
The number of command-line options and their format depend on the actual command. Typically, these options look like -X, where X is a single character. For example, you can use the -l option with the ls command. The command lists the contents of a directory, and the option provides additional details. Here is a result of typing ls -l in a user’s home directory:
total 0
drwxr-xr-x 2 edulaney users 48 2010-09-08 21:11 bin
drwx------ 2 edulaney users 320 2010-09-08 21:16 Desktop
drwx------ 2 edulaney users 80 2010-09-08 21:11 Documents
drwxr-xr-x 2 edulaney users 80 2010-09-08 21:11 public_html
drwxr-xr-x 2 edulaney users 464 2010-09-17 18:21 sdump

If a command is too long to fit on a single line, you can press the backslash key (\) followed by Enter. Then, continue typing the command on the next line. For example, type the following command. (Press Enter after each line.)
cat \
/etc/passwd
The cat command then displays the contents of the /etc/passwd file.
You can concatenate (that is, string together) several shorter commands on a single line by separating the commands by semicolons (;). For example, the following command
cd; ls -l; pwd
changes the current directory to your home directory, lists the contents of that directory, and then shows the name of that directory.
Combining shell commands
You can combine simple shell commands to create a more sophisticated command. For example, suppose that you want to find out whether a device file named sbpcd resides in your system’s /dev directory because some documentation says you need that device file for your CD-ROM drive. You can use the ls /dev command to get a directory listing of the /dev directory and then browse through it to see whether that listing contains sbpcd.
Unfortunately, the /dev directory has a great many entries, so you may find it hard to find any item that has sbpcd in its name. You can, however, combine the ls command with grep and come up with a command line that does exactly what you want. Here’s that command line:
ls /dev | grep sbpcd
The shell sends the output of the ls command (the directory listing) to the grep command, which searches for the string sbpcd. That vertical bar (|) is known as a pipe because it acts as a conduit (think of a water pipe) between the two programs — the output of the first command is fed into the input of the second one.
Controlling command input and output
Most Linux commands have a common feature — they always read from the standard input (usually, the keyboard) and write to the standard output (usually, the screen). Error messages are sent to the standard error (usually to the screen as well). These three devices often are referred to as stdin, stdout, and stderr.
You can make a command get its input from a file and then send its output to another file. Just so you know, the highfalutin term for this feature is input and output redirection or I/O redirection.
Table 3-1 shows the syntax of common I/O redirection commands, and the next few sections explain how to use some of these commands.
Table 3-1
Common Standard I/O Redirections
Task Command Syntax
Send stdout to a file command > file
Send stderr to file command 2> file
Send stdout and stderr to file command > file 2>&1
Read stdin from a file command < file
Read stdin from file.in and
send stdout to file.out
command < file.in > file.
out
Append stdout to the end of a file command >> file
Append stderr to the end of a file command 2>> file
Append stdout and stderr to the end of a file
command >> file 2>&1
Read stdin from the keyboard until the character c
command <<c
Pipe stdout to command2 command | command2
Pipe stdout and stderr to command2
command 2>&1 | command2
Getting command input from a file
If you want a command to read from a file, you can redirect the standard input to come from that file instead of from the keyboard. For example, type the following command:
sort < /etc/passwd
This command displays a sorted list of the lines in the /etc/passwd file. In this case, the less-than sign (<) redirects stdin so that the sort command reads its input from the /etc/passwd file.
Saving command output in a file
To save the output of a command in a file, redirect the standard output to a file. For example, type cd to change to your home directory and then type the following command:
grep typedef /usr/include/* > typedef.out
This command searches through all files in the /usr/include directory for the occurrence of the text typedef — and then saves the output in a file called typedef.out. The greater-than sign (>) redirects stdout to a
file. This command also illustrates another feature of bash: When you use an asterisk (*), bash replaces the asterisk with a list of all filenames in the specified directory. Thus, /usr/include/* means all the files in the /usr/include directory.
If you want to append a command’s output to the end of an existing file instead of saving the output in a new file, use two greater-than signs (>>) like this:
command >> filename
Another interesting use of sending stdout to a file is the use of the cat command to quickly prepare small text files. For example, suppose that you want to create a new text file to store lines of text you type until you type ZZ and press Enter. Here is how you can accomplish that task:
cat <<ZZ > input.txt
After you type this command, you can keep typing lines and then type ZZ on a line when you are finished. Everything you type is saved in the file input.txt.
Saving error messages in a file
Sometimes you type a command, and it generates a lot of error messages that scroll by so fast you can’t tell what’s going on. One way to see all the error messages is to save them in a file so that you can see what the heck happened. You can do that by redirecting stderr to a file.
For example, type the following command:
find / -name COPYING -print 2> finderr
This command looks through the file system for files named COPYING and saves all the error messages (if there are any) in the finderr file. The number 2 followed by the greater-than sign (2>) redirects stderr to a file.
If you want to simply discard the error messages instead of saving them in a file, use /dev/null as the filename, like this:
find / -name COPYING -print 2> /dev/null
That /dev/null is a special file — often called the bit bucket and sometimes glorified as the Great Bit Bucket in the Sky — that simply discards whatever it receives. So now you know what they mean when you hear phrases, such as “Your mail probably ended up in the bit bucket.”
Typing less with automatic command completion
Many commands take a filename as an argument. To view the contents of the /etc/modprobe.conf text file, for example, type the following command:
cat /etc/modprobe.conf
The cat command displays the /etc/modprobe.conf file. For any command that takes a filename as an argument, you can use a bash feature to avoid having to type the entire filename. All you have to type enough characters to uniquely identify the file in its directory.
To see an example, type cat /etc/mod but don’t press Enter; press Tab instead. bash automatically completes the filename, so the command becomes cat /etc/modprobe.conf. Now press Enter to run the command.
Whenever you type a filename, press Tab after the first few characters of the filename. bash probably can complete the filename so that you don’t have to type the entire name. If you don’t enter enough characters to uniquely identify the file, bash beeps. Just type a few more characters and press Tab again.
Going wild with asterisks and question marks
You can avoid typing long filenames another way. (After all, making less work for users is why we use computers, isn’t it?)
This particular trick involves using the asterisk (*) and question mark (?). These special characters are wildcards because they match zero or more characters in a line of text.
If you know MS-DOS, you may have used commands such as COPY *.* A: to copy all files from the current directory to the A: drive. bash accepts similar wildcards in filenames. As you expect, bash provides many more wildcard options than the MS-DOS command interpreter does. Of course, newer computers (particularly notebook computers and especially netbooks) don’t have A and B drives anymore. That deprives an entire generation of the fun of trying to copy a large file onto floppy disks!
You can use three types of wildcards in bash:
  • Asterisk (*): Matches zero or more characters in a filename. That means * denotes all files in a directory.
  • Question mark (?): Matches any single character. If you type test?, that matches any five-character text that begins with test.
  • Set of characters in brackets: Matches any single character from that set. The string [aB], for example, matches only files named a or B, The string [aB]*, though, matches any filename that starts with a or B.
Wildcards are handy when you want to do something to many files. For example, to copy all the files from the /media/cdrom directory to the current directory, type the following:
cp /media/cdrom/*
bash replaces the wildcard character * with the names of all the files in the /media/cdrom directory. The period at the end of the command represents the current directory.
You can use the asterisk with other parts of a filename to select a more specific group of files. Suppose you want to use the grep command to search for the text typedef struct in all files of the /usr/include directory that meet the following criteria:
  • The filename starts with s
  • The filename ends with .h
The wildcard specification s*.h denotes all filenames that meet these criteria. Thus you can perform the search with the following command:
grep “typedef struct” /usr/include/s*.h
The string contains a space that you want the grep command to find, so you have to enclose that string in quotation marks. That way, bash doesn’t try to interpret each word in that text as a separate command-line argument.
The question mark (?) matches a single character. Suppose that you have four files — image1.pcx, image2.pcx, image3.pcx, and image4.pcx — in the current directory. To copy these files to the /media/floppy directory, use the following command:
cp image?.pcx /media/floppy
bash replaces the single question mark with any single character and copies the four files to /media.
The third wildcard format — [ . . . ] — matches a single character from a specific set of characters enclosed in square brackets. You may want to combine this format with other wildcards to narrow the matching filenames to a smaller set. To see a list of all filenames in the /etc/X11/xdm directory that start with x or X, type the following command:
ls /etc/X11/xdm/[xX]*
Repeating previously typed commands
To make repeating long commands easy for you, bash stores up to 500 old commands as part of a command history (basically just a list of old commands). To see the command history, type history. bash displays a numbered list of the old commands, including those that you entered during previous logins.
If the command list is too long, you can limit the number of old commands that you want to see. For example, to see only the 10 most recent commands, type this command:
history 10
To repeat a command from the list that the history command shows, simply type an exclamation point (!), followed by that command’s number. To repeat command number 3, type !3.
You can repeat a command without knowing its command number. Suppose you typed more /usr/lib/X11/xdm/xdm-config a few minutes ago and now you want to look at that file again. To repeat the previous more command, type the following:
!more
Often, you may want to repeat the last command that you just typed, perhaps with a slight change. For example, you may have displayed the contents of the directory by using the ls -l command. To repeat that command, type two exclamation points as follows:
!!
Sometimes, you may want to repeat the previous command but add extra arguments to it. Suppose that ls -l shows too many files. Simply repeat that command but pipe the output through the more command as follows:
!! | more
bash replaces the two exclamation points with the previous command and then appends | more to that command.
Here’s the easiest way to recall previous commands: Just press the up-arrow key, and bash keeps going backward through the history of commands you previously typed. To move forward in the command history, press the downarrow key.
next Discovering and Using Linux Commands
Share this article :

0 comments:

Post a Comment

 
Support : Creating Website | Johny Template | Mas Template
Copyright © 2011. Linux - All Rights Reserved
Template Created by Creating Website Published by Mas Template
Proudly powered by Blogger