previous Commanding the Shell
1 ? S 0:01 init [5]
2 ? SN 0:00 [ksoftirqd/0]
3 ? S< 0:00 [events/0]
4 ? S< 0:00 [khelper]
9 ? S< 0:00 [kthread]
19 ? S< 0:00 [kacpid]
75 ? S< 0:00 [kblockd/0]
115 ? S 0:00 [pdflush]
116 ? S 0:01 [pdflush]
118 ? S< 0:00 [aio/0]
117 ? S 0:00 [kswapd0]
711 ? S 0:00 [kseriod]
1075 ? S< 0:00 [reiserfs/0]
2086 ? S 0:00 [kjournald]
2239 ? S<s 0:00 /sbin/udevd -d
. . . lines deleted . . .
6374 ? S 1:51 /usr/X11R6/bin/X :0 -audit 0 -auth /var/lib/gdm/:0.Xauth
-nolisten tcp vt7
6460 ? Ss 0:02 /opt/gnome/bin/gdmgreeter
6671 ? Ss 0:00 sshd: edulaney [priv]
6675 ? S 0:00 sshd: edulaney@pts/0
6676 pts/0 Ss 0:00 -bash
6712 pts/0 S 0:00 vsftpd
14702 ? S 0:00 pickup -l -t fifo -u
14752 pts/0 R+ 0:00 ps ax --cols 132
As you can see, the date command alone displays the current date and time.
Processing files
86
cat > simple
#!/bin/sh
echo “This script’s name is: $0”
echo Argument 1: $1
echo Argument 2: $2
echo “This script’s name is: $0”
echo Argument 1: $1
echo Argument 2: $2
This script’s name is: ./simple
Argument 1: one
Argument 2: two
This script’s name is: ./simple
Argument 1: This is one argument
Argument 2: second-argument
You type Linux commands at the shell prompt. By Linux commands, I mean some of the commands that the bash shell understands as well as the command-line utilities that come with Linux. In this section, I introduce you to a few major categories of Linux commands.
I can’t cover every single Linux command in this chapter, but I want to give you a feel for the breadth of the commands by showing you common Linux commands. Table 3-2 lists common Linux commands by category. Before you start memorizing any Linux commands, browse this table.
Table 3-2 | Essential Linux Commands |
Command Name | Action |
Help and Abbreviations | |
apropos | Find online manual pages for a specified keyword |
info | Display online help information about a specified command |
man | Display online help information |
whatis | Search for complete words only and find the online manual pages |
alias | Define an abbreviation for a long command |
type | Show the type and location of a command |
unalias | Delete an abbreviation defined using alias |
Managing Files and Directories | |
cd | Change the current directory |
chmod | Change file permissions |
chown | Change the file owner and group |
cp | Copy files |
ln | Create symbolic links to files and directories |
ls | Display the contents of a directory |
mkdir | Create a directory |
mv | Rename a file and move the file from one directory to another |
rm | Delete files |
rmdir | Delete directories |
pwd | Display the current directory |
touch | Update a file’s timestamp |
Finding Files | |
find | Find files based on specified criteria, such as name and size |
locate | Find files using a periodically updated filename database (the database is created by the updatedb program.) |
whereis | Finds files based in the typical directories where executable (also known as binary) files are located |
which | Find files in the directories listed in the PATH environment variable |
Processing Files | |
cat | Display a file on standard output (can be used to concatenate several files into one big file) |
cut | Extract specified sections from each line of text in a file |
dd | Copy blocks of data from one file to another (used to copy data from devices) |
diff | Compare two text files and find any differences |
expand | Convert all tabs to spaces |
file | Display the type of data in a file |
fold | Wrap each line of text to fit a specified width |
grep | Search for regular expressions in a text file |
less | Display a text file one page at a time (go backward by pressing b) |
lpr | Print files |
more | Display a text file, one page at a time (goes forward only) |
nl | Number all nonblank lines in a text file and print the lines to standard output |
paste | Concatenate corresponding lines from several files |
patch | Update a text file using the differences between the original and revised copy of the file |
sed | Copy a file to standard output while applying specified editing commands |
sort | Sort lines in a text file |
split | Break up a file into several smaller files with specified size |
tac | Reverse a file (last line first and so on) |
tail | Display the last few lines of a file |
tr | Substitute one group of characters for another throughout a file |
Processing Files | |
uniq | Eliminate duplicate lines from a text file |
wc | Count the number of lines, words, and characters in a text file |
zcat | Display a compressed file (after decompressing) |
zless | Display a compressed file one page at a time (go backward by pressing b) |
zmore | Display a compressed file one page at a time |
Archiving and Compressing Files | |
compress | Compress files |
cpio | Copy files to and from an archive |
gunzip | Decompress files compressed with GNU Zip (gzip) |
gzip | Compress files using GNU Zip |
tar | Create an archive of files in one or more directories (originally meant for archiving on tape) |
uncompress | Decompress files compressed with compress |
Managing Files | |
bg | Run an interrupted process in the background |
fg | Run a process in the foreground |
free | Display the amount of free and used memory in the system |
halt | Shut down Linux and halt the computer |
kill | Send a signal to a process (usually used to terminate a process) |
ldd | Display the shared libraries needed to run a program |
nice | Run a process with a lower priority (referred to as nice mode) |
ps | Display a list of currently running processes |
printenv | Display the current environment variables |
pstree | Show parent-child process relationships |
reboot | Stop Linux and then restart the computer |
shutdown | Shut down Linux |
top | Display a list of most processor- and memory-intensive processes |
uname | Display information about the system and the Linux kernel |
Managing Users | |
chsh | Change the shell (command interpreter) |
groups | Print the list of groups that include a specified user |
id | Display the user and group ID for a specified username |
passwd | Change the password |
su | Start a new shell as another user (the other user is assumed to be root when the command is invoked without any argument) |
Managing the File System | |
df | Summarize free and available space in all mounted storage devices |
du | Display disk usage information |
fdformat | Format a floppy disk |
fdisk | Partition a hard drive |
fsck | Check and repair a file system |
mkfs | Create a new file system |
mknod | Create a device file |
mkswap | Create a swap space for Linux in a file or a hard drive partition |
mount | Mount a device (for example, the CD-ROM) on a directory in the file system |
swapoff | Deactivate a swap space |
swapon | Activate a swap space |
sync | Writes buffered (saved in memory) data to files |
tty | Display the device name for the current terminal |
umount | Unmount a device from the file system |
Dates and Times | |
cal | Display a calendar for a specified month or year |
date | Display the current date and time or set a new date and time |
Becoming root (superuser)
When you want to do anything that requires a high privilege level (for example, administering your system), you have to become root. Normally, you log in as a regular user with your everyday username. When you need the privileges of the superuser, though, use the following command to become root:
su -
That’s su followed by a space and the minus sign (or hyphen). The shell then prompts you for the root password. Type the password and press Enter.
After you’ve finished with whatever you want to do as root (and you have the privilege to do anything as root), type exit to return to your normal username.
Instead of becoming root by using the su - command, you can also type sudo followed by the command that you want to run as root. In Ubuntu, you must use the sudo command because you don’t get to set up a root user when you install Ubuntu. If you’re listed as an authorized user in the /etc/sudoers file, sudo executes the command as if you were logged in as root. Type man sudoers to read more about the /etc/sudoers file.
Managing processes
Every time the shell executes a command that you type, it starts a process. The shell itself is a process as are any scripts or programs that the shell runs.
Use the ps ax command to see a list of processes. When you type ps ax, bash shows you the current set of processes. Here are a few lines of output when I type ps ax --cols 132. (I included the --cols 132 option to ensure that you can see each command in its entirety.)
PID TTY STAT TIME COMMAND 1 ? S 0:01 init [5]
2 ? SN 0:00 [ksoftirqd/0]
3 ? S< 0:00 [events/0]
4 ? S< 0:00 [khelper]
9 ? S< 0:00 [kthread]
19 ? S< 0:00 [kacpid]
75 ? S< 0:00 [kblockd/0]
115 ? S 0:00 [pdflush]
116 ? S 0:01 [pdflush]
118 ? S< 0:00 [aio/0]
117 ? S 0:00 [kswapd0]
711 ? S 0:00 [kseriod]
1075 ? S< 0:00 [reiserfs/0]
2086 ? S 0:00 [kjournald]
2239 ? S<s 0:00 /sbin/udevd -d
. . . lines deleted . . .
6374 ? S 1:51 /usr/X11R6/bin/X :0 -audit 0 -auth /var/lib/gdm/:0.Xauth
-nolisten tcp vt7
6460 ? Ss 0:02 /opt/gnome/bin/gdmgreeter
6671 ? Ss 0:00 sshd: edulaney [priv]
6675 ? S 0:00 sshd: edulaney@pts/0
6676 pts/0 Ss 0:00 -bash
6712 pts/0 S 0:00 vsftpd
14702 ? S 0:00 pickup -l -t fifo -u
14752 pts/0 R+ 0:00 ps ax --cols 132
In this listing, the first column has the heading PID and shows a number for each process. PID stands for process ID (identification), which is a sequential number assigned by the Linux kernel. If you look through the output of the ps ax command, you see that the init command is the first process and has a PID of 1. That’s why init is referred to as the mother of all processes.
The COMMAND column shows the command that created each process, and the TIME column shows the cumulative CPU time used by the process. The STAT column shows the state of a process — S means the process is sleeping, and R means it’s running. The symbols following the status letter have further meanings; for example < indicates a high-priority process, and + means that the process is running in the foreground. The TTY column shows the terminal, if any, associated with the process.
The process ID, or process number, is useful when you have to forcibly stop an errant process. Look at the output of the ps ax command and note the PID of the offending process. Then, use the kill command with that process number to stop the process. For example, to stop process number 8550, start by typing the following command:
kill 8550
If the process doesn’t stop after five seconds, repeat the command. The next step in stopping a stubborn process is to type kill -INT pid, where pid is the process number. If that doesn’t work, try the following command as a last resort:
The -9 option means send signal number 9 to the process. Signal number 9 is the KILL signal, which should cause the process to exit. You could also type this command as kill -KILL pid, where pid is the process ID.
Working with date and timeYou can use the date command to display the current date and time or set a new date and time. Type date at the shell prompt and you get a result similar to the following:
Fri Mar 14 15:10:07 EST 2010As you can see, the date command alone displays the current date and time.
To set the date, log in as root and then type date followed by the date and time in the MMDDhhmmYYYY format, where each character is a digit. For example, to set the date and time to December 31, 2010 and 9:30 p.m., you type
123121302010
The MMDDhhmmYYYY date and time format is similar to the 24-hour military clock and has the following meaning:- MM is a two-digit number for the month (01 through 12).
- DD is a two-digit number for the day of the month (01 through 31).
- hh is a two-digit hour in 24-hour format (00 is midnight and 23 is 11 p.m.).
- mm is a two-digit number for the minute (00 through 59).
- YYYY is the four-digit year (such as 2010).
The other interesting date-related command is cal. If you type cal without any options, it prints a calendar for the current month. If you type cal followed by a number, cal treats the number as the year and prints the calendar for that year. To view the calendar for a specific month in a specific year, provide the month number (1 = January, 2 = February, and so on) followed by the year. Thus, type cal 8 2010 and you get the calendar for August 2010, as follows:
Processing files
You can search through a text file with grep and view a text file, a screen at a time, with more. For example, to search for my username in the /etc/passwd file, I use
To view the /etc/inittab file a screen at a time, I type
more /etc/inittab
As each screen pauses, I press the spacebar to go to the next page.
Many more Linux commands work on files — mostly on text files, but some commands also work on any file. The sections that follow describe a few of the file-processing tools.
Counting words and lines in a text file
I am always curious about the size of files. For text files, the number of characters is basically the size of the file in bytes (because each character takes up a byte of storage space). What about words and the number of lines, though?
The Linux wc command comes to the rescue. The wc command displays the total number of lines, words, and characters in a text file. For example, type wc /etc/inittab and you see output similar to the following:
97 395 2926 /etc/inittab
In this case, wc reports that 97 lines, 395 words, and 2,926 characters are in the /etc/inittab file. If you simply want to see the number of lines in a file, use the -l option and type wc -l /etc/inittab. The resulting output should be similar to the following:
97 /etc/inittab
As you can see, with the -l option, wc simply displays the line count.
If you don’t specify a filename, the wc command expects input from the standard input. You can use the pipe feature (|) of the shell to feed the output of another command to wc, which can be handy sometimes.
Suppose you want a rough count of the processes running on your system. You can get a list of all processes with the ps ax command, but instead of counting lines manually, just pipe the output of ps to wc and you get a rough count automatically:
ps ax | wc -l 86
Here the ps command produces 86 lines of output. Because the first line simply shows the headings for the tabular columns, you can estimate that about 85 processes are running on your system. (This count probably includes the processes used to run the ps and wc commands as well.)
Sorting text files
You can sort the lines in a text file by using the sort command. To see how the sort command works, first type more /etc/passwd to see the current contents of the /etc/passwd file. Now type sort /etc/passwd to see the lines sorted alphabetically. If you want to sort a file and save the sorted version in another file, you have to use the bash shell’s output redirection feature, like this:
sort /etc/passwd > ~/sorted.text
This command sorts the lines in the /etc/passwd file and saves the output in a file named sorted.text in your home directory.
Substituting or deleting characters from a file
Another interesting command is tr, which substitutes one group of characters for another (or deletes a selected character) throughout a file. Suppose that you have to occasionally use MS-DOS text files on your Linux system. Although you may expect to use a text file on any system without any problems, you find one catch: DOS uses a carriage return followed by a line feed to mark the end of each line whereas Linux uses only a line feed.
On your Linux system, you can get rid of the extra carriage returns in the DOS text file by using the tr command with the -d option. Essentially, to convert the DOS text file named filename.dos to a Linux text file named filename.linux, type the following:
tr -d ‘\015’ < filename.dos > filename.linux
In this command, ‘\015’ denotes the code for the carriage-return character in octal notation.
Splitting a file into several smaller files
The split command is handy for those times when you want to copy a file but the file is too large to fit on a single floppy or send as one e-mail attachment. You can then use the split command to break up the file into multiple smaller files.
By default, split puts 1,000 lines into each file. The new, split files are named by groups of letters such as aa, ab, ac, and so on. You can specify a prefix for the filenames. For example, to split a large file called hugefile. tar into smaller files, use split as follows:
split -b 1440k hugefile.tar part.
This command splits the hugefile.tar file into 1440K chunks. The command creates files named part.aa, part.ab, part.ac, and so on.
To combine the split files back into a single file, use the cat command as follows:
cat part.?? > hugefile.tar
In this case, the two question marks (??) match any two-character extension in the filename. In other words, the filename part.?? matches all filenames such as part.12, part.aa, part.ab, and part.2b.
Writing Shell Scripts
If you’ve ever used MS-DOS, you may remember MS-DOS batch files, which are text files with MS-DOS commands. Similarly, shell scripts are also text files with a bunch of shell commands.
If you aren’t a programmer, you may feel apprehensive about programming, but shell programming can be as simple as storing a few commands in a file. Right now, you might not be up to writing complex shell scripts, but you can certainly try out a simple shell script.
To try your hand at a little shell programming, type the following text at the shell prompt exactly as shown and then press Ctrl+D when you’re finished:
cd cat > simple
#!/bin/sh
echo “This script’s name is: $0”
echo Argument 1: $1
echo Argument 2: $2
Press Ctrl+D. The cd command changes the current directory to your home directory. Then the cat command displays the next line and any other lines you type before pressing Ctrl+D. In this case, I use > simple to send the output to a file named simple. After you press Ctrl+D, the cat command ends, and you see the shell prompt again. You created a file named simple that contains the following shell script:
#!/bin/sh echo “This script’s name is: $0”
echo Argument 1: $1
echo Argument 2: $2
The first line causes Linux to run the bash shell program (of the name /bin/bash). The shell then reads the rest of the lines in the script.
Just as most Linux commands accept command line options, a bash script also accepts command-line options. Inside the script, you can refer to the options as $1, $2, and so on. The special name $0 refers to the name of the script itself.
To run this shell script, first you have to make the file executable (that is, turn it into a program) with the following command:
chmod +x simple
Now type ./simple one two to run the script, and it displays the following output:This script’s name is: ./simple
Argument 1: one
Argument 2: two
The ./ prefix to the script’s name indicates that the simple file is in the current directory.
This script simply prints the script’s name and the first two command-line options that the user types after the script’s name.
Next, try running the script with a few arguments, as follows:
./simple “This is one argument” second-argument third This script’s name is: ./simple
Argument 1: This is one argument
Argument 2: second-argument
The shell treats the entire string in the double quotation marks as a single argument. Otherwise, the shell uses spaces as separators between arguments on the command line.
Most useful shell scripts are more complicated than this simple script, but this easy exercise gives you a rough idea of how to write shell scripts.
Place Linux commands in a file and use the chmod command to make the file executable. VoilĂ ! You created a shell script!
next Navigating the Linux File System
0 comments:
Post a Comment