Appendix B. Useful Commands

The commands on your system form the building blocks that you can glue together in your scripts. The following sections cover some of the more useful commands from a scripting point of view, divided into related sections. The listings here appear in a brief format. As always, however, you can find detailed information on these and other commands by perusing the online documentation.

Because of differences between Unix, Mac OS X, Linux, and the Cygwin environment on Windows, the listings here focus on the most common options for these commands. As always, use the ever-handy online manuals to look up the full documentation on each command.

Navigating the System

These commands help you interact with the operating system.

exit

exit exit_code

Description

Exits the current shell. You can pass an optional exit code, a number. An exit code of 0 (zero) indicates the script executed successfully. A nonzero value indicates an error.

Example

$ exit

Exits the current shell.

Options

None.

file

file options filename

Description

Attempts to classify the type of each file passed on the command line. Usually, the file command does this by reading the first few bytes of a file and looking for matches in a file of magic values, /etc/magic. This isn't really magic but simple comparisons. For example, the file command should be able to determine ASCII text files, executable programs, and other types of files.

The file command does not always classify correctly, but it usually does a good job.

Examples

$ file `which sh`
/bin/sh: symbolic link to `bash'

Prints the type of file of sh. On this system, sh is implemented by bash.

$ file vercompare.py
vercompare.py: a /usr/bin/python script text executable

Checks the type of a Python script.

Options

Option

Usage

-c

Outputs a checking printout of the magic file

-f file

Reads in a given file and then runs the command on each file name in that file, assuming one file name per line

-m file:file:file

Uses the named files as the magic files instead of /etc/magic

kill

kill options process_IDs

Description

Sends a signal to the given process or processes. In most cases, the processes die upon receipt of the signal.

You can send signals only to processes that you own, unless you are logged in as the root user.

Examples

$ kill -SIGKILL 4753

Sends the kill signal (SIGKILL) to process number 4753.

$ kill −9 4754

Sends the kill signal (9) to process number 4754.

$ kill -l
 1) SIGHUP       2) SIGINT       3) SIGQUIT      4) SIGILL
 5) SIGTRAP      6) SIGABRT      7) SIGBUS       8) SIGFPE
 9) SIGKILL     10) SIGUSR1     11) SIGSEGV     12) SIGUSR2
13) SIGPIPE     14) SIGALRM     15) SIGTERM     17) SIGCHLD
18) SIGCONT     19) SIGSTOP     20) SIGTSTP     21) SIGTTIN
22) SIGTTOU     23) SIGURG      24) SIGXCPU     25) SIGXFSZ
26) SIGVTALRM   27) SIGPROF     28) SIGWINCH    29) SIGIO
30) SIGPWR      31) SIGSYS      34) SIGRTMIN    35) SIGRTMIN+1
36) SIGRTMIN+2  37) SIGRTMIN+3  38) SIGRTMIN+4  39) SIGRTMIN+5
40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8  43) SIGRTMIN+9
44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13
48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13
52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9
56) SIGRTMAX-8  57) SIGRTMAX-7  58) SIGRTMAX-6  59) SIGRTMAX-5
60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2  63) SIGRTMAX-1
64) SIGRTMAX

Lists the signals and their numbers.

Options

Option

Usage

-l

Lists the available signals

-number

Sends the given signal by its number, such as 9 for SIGKILL

-signal

Sends the given named signal, such as SIGHUP

man

man options command

Description

Displays the online manual entry for the given command.

Example

$ man man
man(1)                                                                 man(1)

NAME
       man - format and display the on-line manual pages
SYNOPSIS
       man  [-acdfFhkKtwW]  [--path] [-m system] [-p string] [-C config_file]
       [-M pathlist] [-P pager] [-S section_list] [section] name ...

DESCRIPTION
       man formats and displays the on-line manual  pages.   If  you  specify
       section,  man  only looks in that section of the manual.  name is nor-
       mally the name of the manual page, which is typically the  name  of  a
       command,  function,  or  file.   However, if name contains a slash (/)
       then man interprets it as a file specification, so that you can do man
       ./foo.5 or even man /cd/foo/bar.1.gz.

       See  below  for  a  description of where man looks for the manual page
       files.
...

Displays help on the man command.

Options

Options differ by platform. Try the man man command to see the options for your platform.

nohup

nohup command options arguments &

Description

Short for no hangup, the nohup command runs a command and keeps that command running even if you log out. Typically, when you log out, all the commands you launched are terminated if they are still running. The "no hangup" terminology comes from the days when users logged in using a modem over a phone line and would literally hang up the phone when exiting.

Example

$ nohup xclock &
[1] 4833
nohup: appending output to `nohup.out'

Runs the xclock command in the background, preserving the process even if you log out.

Options

None.

printenv

printenv environment_variable

Description

Prints out the value of a given environment variable or all environment variables if you pass no arguments to this command.

Example

$ printenv USER
ericfj

Prints the USER environment variable.

Options

None.

ps

ps options

Description

Prints the status of current processes, depending on the command-line options. With no options, ps lists just the current shell and the ps process. With options, you can list all the processes running on the system.

Note that Berkeley Unix-based systems, including Mac OS X, support a different set of options than System V Unix-based systems. The options to list all processes is aux for Berkeley Unix-based systems and -ef for System V Unix-based systems. Linux systems support both types of options.

Examples

$ ps
  PID TTY          TIME CMD
 4267 pts/2    00:00:00 bash
 4885 pts/2    00:00:00 ps

Lists the current process (the ps command) and its parent shell.

$ ps -ef
UID        PID  PPID  C STIME TTY          TIME CMD
root         1     0  0 09:57 ?        00:00:00 init [5]
root      2046     1  0 08:46 ?        00:00:00 klogd -x
rpc       2067     1  0 08:46 ?        00:00:00 portmap
rpcuser   2087     1  0 08:46 ?        00:00:00 rpc.statd
root      2290     1  0 08:46 ?        00:00:00 /usr/sbin/sshd
root      2340     1  0 08:46 ?        00:00:00 gpm -m /dev/input/mice -t imps2
root      2350     1  0 08:46 ?        00:00:00 crond
xfs       2376     1  0 08:46 ?        00:00:00 xfs -droppriv -daemon
dbus      2414     1  0 08:46 ?        00:00:00 dbus-daemon-1 --system
root      2427     1  0 08:46 ?        00:00:00 cups-config-daemon
...

Lists all processes in System V Unix style (-ef).

$ ps aux
USER       PID %CPU %MEM   VSZ  RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.0  3488  560 ?        S    09:57   0:00 init [5]
root         2  0.0  0.0     0    0 ?        SN   09:57   0:00 [ksoftirqd/0]
root         3  0.0  0.0     0    0 ?        S<   09:57   0:00 [events/0]
root         4  0.0  0.0     0    0 ?        S<   09:57   0:00 [khelper]
root         5  0.0  0.0     0    0 ?        S<   09:57   0:00 [kacpid]
root        27  0.0  0.0     0    0 ?        S<   09:57   0:00 [kblockd/0]
root        28  0.0  0.0     0    0 ?        S    09:57   0:00 [khubd]
root        37  0.0  0.0     0    0 ?        S    09:57   0:00 [pdflush]
root        38  0.0  0.0     0    0 ?        S    09:57   0:00 [pdflush]
root        40  0.0  0.0     0    0 ?        S<   09:57   0:00 [aio/0]
root        39  0.0  0.0     0    0 ?        S    09:57   0:00 [kswapd0]
root       113  0.0  0.0     0    0 ?        S    09:57   0:00 [kseriod]
root       187  0.0  0.0     0    0 ?        S    08:46   0:00 [kjournald]
root      1014  0.0  0.0  1612  448 ?        S<s  08:46   0:00 udevd
...

Lists all processes in Berkeley Unix style (aux).

Options

Option

Usage

-a

Lists information on all processes except group leaders and processes not associated with a terminal

-d

Lists information on all processes except group leaders

-e

Lists information on every process

-f

Lists full information on processes

a

List all processes with a terminal

u

Displays data in the user-oriented format

x

Lists processes without a terminal

sleep

sleep number_of_seconds

Description

Sleeps for a given number of seconds. You can use an m suffix to indicate minutes and an h suffix for hours.

Examples

$ sleep 2

Sleeps for two seconds.

$ sleep 3h

Sleeps for three hours.

Options

None.

type

type options command_name

Description

Determines the type of command, such as a command on disk or a shell built-in command.

Examples

$ type sleep
sleep is /bin/sleep

Returns the type of the sleep command.

$ type type
type is a shell builtin

Returns the type of the type command.

$ type -t type
builtin

Returns the type name of the type command.

$ type -p sleep
/bin/sleep

Returns the path to the sleep command.

$ type -t sleep
file

Returns the type name of the sleep command.

$ type -a true
true is a shell builtin
true is /bin/true

Returns information on all instances found of the true command.

Options

Option

Usage

-a

Searches for all places for a command and lists them all

-f

Don't look for built-in commands

-P

Forces a search over the command path

-p

Returns the name of the file for the command or nothing if the command is built in

-t

Returns a one-word type of the command, either alias, built-in, file, function, or keyword

uname

uname option

Description

Prints information on the system. Short for Unix name.

Examples

$ uname -p
powerpc

Lists the processor type.

$ uname
Darwin

Lists the Unix name.

$ uname -o
GNU/Linux

Lists the OS name.

$ uname -s
Linux

Lists the kernel name (OS name, really).

$ uname --hardware-platform
i386

Lists the hardware platform, similar to the processor type.

Options

Option

Usage

-a

Prints all information

-o

Prints the operating system

-p

Lists the processor type

-s

Prints the kernel name

who

who options files

Description

Shows who is logged on, as well as information about the system.

Examples

$ who am i
ericfj   pts/1        Jan 16 15:28 (:0.0)

Lists who the user is.

$ who -b
         system boot  Jan 16 08:46

Lists the last boot time.

$ who
ericfj   :0           Jan 16 15:28
ericfj   pts/1        Jan 16 15:28 (:0.0)
ericfj   pts/2        Jan 16 15:28 (:0.0)
ericfj   pts/3        Jan 16 15:28 (:0.0)

Lists all logged-in users. Note how it thinks the same user is logged in multiple times. The pts 1, 2, and 3 values come from shell windows.

$ who -H
NAME     LINE         TIME         COMMENT
ericfj   :0           Jan 16 15:28
ericfj   pts/1        Jan 16 15:28 (:0.0)
ericfj   pts/2        Jan 16 15:28 (:0.0)
ericfj   pts/3        Jan 16 15:28 (:0.0)

Adds a header line to the normal who output.

$ who -q
ericfj ericfj ericfj ericfj
# users=4

Lists in quick mode.

$ who -r
         run-level 5  Jan 16 08:46                   last=S

Lists the system run level. On Linux, run level 5 usually means the X Window System has been started for graphics.

Options

Option

Usage

am i

Returns your username

-a

Same as all the other options combined

-b

Prints time of last system boot

-d

Prints dead processes

-H

Inserts a line of column headings

-l

Prints the system login process

-p

Lists processes launched from the init command that are still running

-q

Quick mode, lists user names and a count

-r

Prints the current run level

-s

Short output, default

-t

Prints last system clock change

-T

Adds a +, -, or ? for the status of each user

-u

Prints users logged in

whoami

whoami

Description

Prints out the username of the current user.

Examples

$ whoami
ericfj

Lists who the user is.

Options

None.

Working with Files and Directories

Many scripts need to work with files. These commands are among the oldest in Unix history, as files have always been important.

basename

basename path suffix

Description

Extracts the base file name from a long path. The optional suffix allows you to extract a file-name extension, such as .txt.

Examples

$ basename /home/ericfj/rpms/thunderbird-1.0-1.fc3.i386.rpm
thunderbird-1.0-1.fc3.i386.rpm
$ basename /home/ericfj/rpms/thunderbird-1.0-1.fc3.i386.rpm .rpm
thunderbird-1.0-1.fc3.i386

Options

None.

cat

cat options files

Description

Concatenates files to standard output. You can concatenate one or more files. With just one file, cat prints the file to standard output, and you can use this to display the contents of short files. With multiple files, cat prints them all to standard output, allowing you to combine files together. You'll often use output redirection such as > or >> with cat.

Examples

$ cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
...

Shows the contents of the file /etc/password.

$ cat /etc/shells
/bin/sh
/bin/bash
/sbin/nologin
/bin/ash
/bin/bsh
/bin/ksh
/usr/bin/ksh
/usr/bin/pdksh
/bin/tcsh
/bin/csh
/bin/zsh

Shows the contents of the file /etc/shells.

Options

Options differ by platform. See your online documentation for details on your platform.

chmod

chmod option mode filenames

Description

Changes the mode, the permissions, on a file.

The following table lists the numeric modes for the chmod command. Note that these modes are all in octal, base 8, numbers.

Value

Meaning

400

Owner has read permission.

200

Owner has write permission.

100

Owner has execute permission.

040

Group has read permission.

020

Group has write permission.

010

Group has execute permission.

004

All other users have read permission.

002

All other users have write permission.

001

All other users have execute permission.

You then need to add these values together, as in the following table.

Value

Meaning

400

Owner has read permission.

200

Owner has write permission.

100

Owner has execute permission.

040

Group has read permission.

020

Group has write permission.

004

All other users have read permission.

  

764

Total

This example results in a total of 764.

In addition to the numeric modes, you can use the symbolic modes, as shown in the following table.

Value

Meaning

u

The user who is the owner.

g

Group.

o

All other users.

all

Sets permissions for all users. Can also use a.

+

Adds the permissions following.

-

Removes (subtracts) the permissions following.

=

Assigns just the permissions following and removes any old permissions on the files.

r

Read permission.

w

Write permission.

x

Execute permission.

l

Locks the files during access.

Examples

$ chmod a+x script1

Adds execute permissions for all users to script1.

$ chmod 764 script1

Allows the user to read, write, and execute script1, the members of the group to read and write, and everyone else to just read.

Options

Option

Usage

-R

Goes recursively through all subdirectories and files, changing the permissions on all

chown

chown option owner files

Description

Changes the ownership of files. You must be the owner of the file or files.

Example

$ chown ericfj  script1 script2 script3

Options

Option

Usage

-R

Goes recursively through all subdirectories and files, changing the ownership on all

cp

cp options sourcefiles destination

Description

Copies a file or files. If you copy multiple files, then the destination must be a directory. If you just copy one file, then the destination can be a file name or a directory.

Examples

$ cp * /usr/local/bin

Copies all files in the current directory to /usr/local/bin.

$ cp report.txt report.backup

Copies a file to a backup file.

Options

Option

Usage

-i

Interactive mode that prompts you before overwriting a file

-f

Forces a copy by removing the target files if needed and trying again

-p

Preserves file permissions on the copy

-r

Same as -R

-R

Goes recursively through all subdirectories and files, copying all

df

df options filesystems_or_directories

Description

Short for disk free, df returns the amount of space used and available on all mounted file systems. With no arguments, df lists information for all mounted file systems. You can pass the name of the file systems, either the file system or the mount point, to list information on just those file systems. You can also provide the name of a directory, and df displays information on the file system that contains that directory. This is very handy so you don't have to remember all the file system names.

For example, an all-too-frequent problem occurs when the /tmp, or temporary, directory fills up. On some systems, /tmp is mounted as its own file system (and disk partition). On other systems, /tmp is part of the root, or /, file system. You can pass /tmp as the name of a file system to the df command. Even if /tmp is not mounted as part of its own file system, the df command will display information on the file system holding /tmp.

Examples

$ df
Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/hda2             24193540   3979392  18985176  18% /
/dev/hda1               101086     10933     84934  12% /boot
none                    501696         0    501696   0% /dev/shm
/dev/hda5             48592392  26391104  19732904  58% /home2

Lists all mounted file systems.

$ df /tmp
Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/hda2             24193540   3979392  18985176  18% /

Lists the information for the file system containing /tmp.

Options

Option

Usage

-k

Returns the output in 1K blocks

-l

Displays information on local file systems only.

du

du filenames

Description

Lists the amount of disk space used for a given set of files or directories. Technically, du estimates the amount of disk usage. You can use du on a file or a directory. The command will traverse all subdirectories and report on the total for each directory it examines. Command-line options can modify this behavior.

Examples

$ du
360     ./mrtg/html
632     ./mrtg/working
1100    ./mrtg
328     ./marketing
88      ./web_files
18860   ./figures/tmp/chap14
19460   ./figures/tmp
20      ./figures/.xvpics
136     ./figures/chap1
1416    ./figures/chap2
9872    ./figures/chap14_1
8996    ./figures/chap14_2
53508   ./figures
2228    ./scripts/foo
37284   ./scripts
18688   ./chapter12
5076    ./author_review
122364  .

Shows the size of the current directory and all subdirectories.

$ du -s
122364  .

Runs the same command but in silent mode, showing just a total size.

Options

Option

Usage

-a

Prints a line of output for each file, rather than just one line per directory.

-s

Silent mode. Displays only the total line.

find

find start_at conditions actions

Description

The find command searches the files on disk from a given starting location, start_at, looking for files and directories that match the given conditions and then taking the given actions, such as printing out the file names.

This is a very complex command. It is often used to make backups (finding the list of files modified since the last backup), report on large files (finding the list of files larger than a certain size), or in fascist environments, remove all old files (finding all files older than a given date and then removing them).

In some cases, you'll want to combine the output of find with other commands. But the number of actions available to the find command itself means that you can often just run the command alone.

Older versions of the find command did not print out the names found, in a very stupid default. Most modern versions of find print out the names of the files or directories found. If your system uses the stupid default, add a -print option at the end of the find command to print out the results.

Examples

$ find . -ctime −1 -print
./scripts
./scripts/nohup.out
./583204_appb_efj.doc

Finds all files in the current directory and below that have been modified in the last day. The -print option is not necessary.

$ find $HOME -name 'script*'
./scripting_outline.txt
./scripts
./scripts/script1
./scripts/script3
./scripts/script2
./scripts/script_q
./scripts/script1.sh
./scripts/script_y
./scripts/script5
./scripts/script4
./scripts/script8
./scripts/script6
./scripts/script7
./scripts/script9
./scripts/script10
./scripts/script11
./scripts/script12
./scripts/script13
./scripts/script14
./scripts/script15
./scripts/script16
./scripts/script17
./scripts/script18

Finds all files in the user's home directory (and below) with a name that starts with script.

Options

See the online manual entry on find, as there are a huge number of options that differ by platform.

grep

grep options pattern files

Description

Searches for text based on a pattern (called a regular expression). The lines of text that match the pattern are printed. You need to tell grep what to look for and which files to examine.

Other related commands include fgrep and egrep.

Examples

$ grep while *
whilepipe:while read filename; do

Looks for all files in the current directory for the text while. This is found in one file.

$ grep -h while *
while read filename; do

Performs the same search but does not output the names of the files.

$ grep -o while *
whilepipe:while

Performs the same search but outputs only the pattern match.

Options

Option

Usage

-h

Does not return the names of the files.

-i

Ignores case when searching.

-l

Just lists the file names, not the matched text.

-q

Quiet mode. Used when you just want to check the program's exit status.

-s

Suppresses error messages.

-v

Looks for lines that do not contain the match.

In addition to these options, you'll find a number of platform-specific options in your online manuals.

head

head options files

Description

Displays the beginning of a text file. By default, head prints out the first ten lines in the file.

Examples

$ head /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
news:x:9:13:news:/etc/news:

Lists the first ten lines of /etc/passwd.

$ head −2 /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin

Lists the first two lines of /etc/passwd.

Options

Option

Usage

-number

Displays the given number of lines

ls

ls options files_or_directories

Description

Lists file names. You can display a long listing or a short listing. This is a surprisingly complex command for such a simple purpose.

Examples

$ ls /usr/local
bin  etc  games  include  lib  libexec  man  sbin  share  src

Lists the files in /usr/local.

$ ls -CF /usr/local
bin/  etc/  games/  include/  lib/  libexec/  man/  sbin/  share/  src/

Lists the files in /usr/local with a slash after directory names, an @ for links, and a * for executable files.

$ ls -l /usr/local
total 80
drwxr-xr-x  2 root root 4096 Dec  9 00:00 bin
drwxr-xr-x  2 root root 4096 Aug 12 12:02 etc
drwxr-xr-x  2 root root 4096 Aug 12 12:02 games
drwxr-xr-x  2 root root 4096 Aug 12 12:02 include
drwxr-xr-x  2 root root 4096 Aug 12 12:02 lib
drwxr-xr-x  2 root root 4096 Aug 12 12:02 libexec
drwxr-xr-x  3 root root 4096 Nov 15 20:35 man
drwxr-xr-x  2 root root 4096 Aug 12 12:02 sbin
drwxr-xr-x  4 root root 4096 Nov 15 17:17 share
drwxr-xr-x  2 root root 4096 Aug 12 12:02 src

Presents a long listing of the files in /usr/local.

Options

Option

Usage

−1

Lists one item per line

-a

Lists all files, including hidden (dot) files

-b

Prints octal values of characters you don't see

-c

Lists by last modified time

-C

Lists in columns (the default)

-d

Lists only the name of directories, not the files in them

-F

Appends an indicator to show directories (/), executable files (*), links (@), and pipes (|)

-g

Lists in long form but without the owner's name

-l

Lists information in long form

-L

Lists the names links are linked to

-m

Lists files across the screen separated by commas

-n

Lists in long form, but with user and group numbers instead of names

-o

Lists in long form but omits the group

-q

Lists nonprintable characters as a question mark, ?

-r

Lists items in reverse order

-R

Recursively goes into all subdirectories

-s

Lists file sizes in blocks, not bytes

-t

Sorts the files by the modification time

-u

Sorts by last access time

-x

Sorts entries by lines instead of by columns

In addition to these options, you'll find a number of platform-specific options in your online manuals.

mkdir

mkdir options directory_names

Description

Creates one or more directories.

Examples

$ mkdir tmp

Creates directory tmp.

$ mkdir -m 664 tmp
$ ls -dl tmp
drw-rw-r--  2 ericfj ericfj 4096 Jan 16 20:58 tmp

Creates directory tmp with the given permissions (verified by the ls command).

Options

Option

Usage

-m mode

Defines the permissions mode for the new directories

mv

mv options source target

Description

Moves a file or files. If you move multiple files, the target must be a directory. If you move one file, the target can be a file name or a directory name (naming the directory in which to move the file).

Examples

$ mv *.html old_web

Moves all HTML files to the directory named old_web.

$ mv index.htm index.html

Renames the file index.htm to index.html.

Options

Option

Usage

-f

Forces the move, ignoring the -i option

-i

Asks for confirmation if the command would overwrite a file

rm

rm options files

Description

Removes (deletes) files.

Examples

$ rm -rf ./tmp

Removes the tmp subdirectory and all files and directories in it.

$ rm -i index.html
rm: remove regular file `index.html'? y

Removes the file named index.html but requires you to confirm the deletion (a smart option).

Options

Option

Usage

-f

Forces the move, ignoring the -i option

-i

Asks for confirmation if the command would overwrite a file

-r

Recursively removes files and directories

rmdir

rmdir options directories

Description

Removes (deletes) directories. The directories must be empty to be deleted. Watch out for hidden files (files with names that start with a period), because you won't see these files, but their presence will stop rmdir from deleting a directory.

Examples

$ rmdir tmp

Removes the subdirectory tmp.

Option

Option

Usage

-p

Removes the directory and any parent directories as long as they are empty

tail

tail option files

Description

Prints out the last ten lines of a file. You can define the number of lines. The -f option tells the tail command to output forever, checking the file periodically for new lines and then printing those. This is most useful with log files for a service or when building a huge software package.

Examples

$ tail /etc/passwd
mailnull:x:47:47::/var/spool/mqueue:/sbin/nologin
smmsp:x:51:51::/var/spool/mqueue:/sbin/nologin
pcap:x:77:77::/var/arpwatch:/sbin/nologin
apache:x:48:48:Apache:/var/www:/sbin/nologin
squid:x:23:23::/var/spool/squid:/sbin/nologin
webalizer:x:67:67:Webalizer:/var/www/usage:/sbin/nologin
xfs:x:43:43:X Font Server:/etc/X11/fs:/sbin/nologin
ntp:x:38:38::/etc/ntp:/sbin/nologin
gdm:x:42:42::/var/gdm:/sbin/nologin
ericfj:x:500:500:Eric Foster-Johnson:/home2/ericfj:/bin/bash

Lists the last ten lines of /etc/passwd.

$ tail −2 /etc/passwd
gdm:x:42:42::/var/gdm:/sbin/nologin
ericfj:x:500:500:Eric Foster-Johnson:/home2/ericfj:/bin/bash

Lists the last two lines of /etc/passwd.

$ tail -f /var/log/dmesg
EXT3 FS on hda1, internal journal
EXT3-fs: mounted filesystem with ordered data mode.
SELinux: initialized (dev hda1, type ext3), uses xattr
SELinux: initialized (dev tmpfs, type tmpfs), uses transition SIDs
kjournald starting.  Commit interval 5 seconds
EXT3 FS on hda5, internal journal
EXT3-fs: mounted filesystem with ordered data mode.
SELinux: initialized (dev hda5, type ext3), uses xattr
Adding 4096564k swap on /dev/hda3.  Priority:-1 extents:1
SELinux: initialized (dev binfmt_misc, type binfmt_misc), uses genfs_contexts

Outputs the contents of the log file dmesg forever (until killed).

Options

Option

Usage

-number

Prints the given number of lines.

-f

Forever or follow mode. Prints the end of the file as new lines are added. Usually used with log files.

-s seconds

Sleeps for the given number of seconds between checks. Used only with -f.

touch

touch options files

Description

By touching a file, you modify it. (Think of what happens when children touch something.) At the most basic level, touch is used to update the time a file was last modified. You can also set the time to a particular value.

Typically, if a file doesn't exist, touch will create it, making it 0 (zero) bytes in size.

To set the time to a particular value, use one of the following formats: CCYYMMddhhmm, YYMMddhhmm, MMddhhmm, or MMddhhmmYY. The following table explains the formats.

Format

Holds

MM

Month, 1–12

dd

Day of month, 1–31

hh

Hour of the day, 00–23

mm

Minute of the hour, 00–59

CC

Century, such as 20

YY

Year in century, such as 06 for 2006

Examples

$ touch *.c

Updates the modification date for all files ending in .c to the current time.

$ touch -t 201012251159 mozilla_coffee_order.html
$ ls -l mozilla_coffee_order.html
-rw-rw-r--  1 ericfj ericfj 7663 Dec 25  2010 mozilla_coffee_order.html

Sets the modification time to Christmas in 2010 for the given file and verifies the time with the ls command.

Options

Option

Usage

-a

Changes only the last access time

-c

Does not create a new file if none exists

-m

Changes only the modification time

-t timestamp

Sets the time to the given timestamp

Manipulating Text

In addition to working with files and directories, there are quite a few commands that manipulate text. (Some of these distinctions are arbitrary.) These commands are used primarily to output text, while the commands in the following Transforming Data section are used primarily for modifying text.

awk

awk '/somedata/ { actions }' filenames

Description

The awk command runs a program, typically placed between single quotes (as shown here) or in a separate file. The awk command searches the files passed to it for the pattern /somedata/ and then applies the given actions to all lines matching the pattern.

See Chapter 7 for a lot of information on awk. This is a very complex command.

Example

$  awk -F':' '/eric/ { print $5 }' /etc/passwd
Eric Foster-Johnson

Searches for the pattern eric in the file /etc/passwd and then prints out the fifth field from all matching lines. Sets the field separator to a colon (:) instead of the default spaces because of the format of the /etc/passwd file.

Options

Option

Usage

-f program_file

Loads the awk program from the given file

-F field_separator

Changes the default field separator to the given value

echo

echo option text

Description

Echoes its data to standard output. If you place the data in double quotes, echo expands variables inside text strings.

Examples

$ echo $HOME
/home2/ericfj

Lists the user's home directory.

$ echo "User ${USER}'s home directory is ${HOME}."
User ericfj's home directory is /home2/ericfj.

Lists the user's username and home directory.

$ echo hello    there
hello there

Outputs the two arguments, with one space in between.

$ echo "hello    there"
hello    there

Outputs the same data with the embedded spaces included.

$ echo -n "What is your name? "
What is your name?

Outputs the question and leaves the cursor after the question mark.

Options

Option

Usage

-n

Doesn't output a new line

Transforming Data

These commands modify data, usually assuming that the data are all text.

cut

cut options files

Description

Extracts data as columns, based on a field separator, usually a space.

Example

$ cut -d':' -f1,5 /etc/passwd
root:root
bin:bin
daemon:daemon
adm:adm
lp:lp
sync:sync
shutdown:shutdown
halt:halt
mail:mail
news:news
uucp:uucp
operator:operator
games:games
gopher:gopher
ftp:FTP User
nobody:Nobody
dbus:System message bus
vcsa:virtual console memory owner
nscd:NSCD Daemon
rpm:
haldaemon:HAL daemon
netdump:Network Crash Dump user
sshd:Privilege-separated SSH
rpc:Portmapper RPC user
rpcuser:RPC Service User
nfsnobody:Anonymous NFS User
mailnull:
smmsp:
pcap:
apache:Apache
squid:
webalizer:Webalizer
xfs:X Font Server
ntp:
gdm:
ericfj:Eric Foster-Johnson

Cuts the first and fifth fields from the /etc/passwd file.

Options

Option

Usage

-d Delimiter

Sets the field separator to the given delimiter character. Usually, you need to place this in quotes.

-s

Suppresses the output of lines that don't have a field separator.

sed

sed options 'program' files

Description

A stream, or noninteractive, text editor. Use sed to modify files in a programmed manner.

See Chapter 6 for a lot of information on sed.

Example

$ cat /etc/passwd | sed 'p' | head −10
root:x:0:0:root:/root:/bin/bash
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
sync:x:4:65534:sync:/bin:/bin/sync

Sends the contents of the /etc/passwd file to the sed command. The 'p' program tells sed to print out the lines. This output is redirected to the head command, which shows only the first ten lines.

Options

Option

Usage

-e ' script'

Uses the given script as the sed program

-f script_file

Loads the script from the given file

-n

Disables the automatic printing

sort

sort options files

Description

Sorts files line by line.

Examples

$ printenv | sort | head −4
COLORTERM=gnome-terminal
DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-LFVLT6j4Fj
DESKTOP_SESSION=default
DISPLAY=:0.0

Sorts the data returned by printenv.

$ printenv | sort | sort -c
$ printenv |  sort -c
sort: -:2: disorder: HOSTNAME=kirkwall

Shows how the -c option works. If the data are sorted, -c tells the sort command to do nothing. Otherwise, it generates an error on the first out-of-order line.

Options

Option

Usage

-b

Ignores leading blank space or tab characters.

-c

Checks if the file is sorted. Does not sort.

-d

Sorts in dictionary order, ignoring punctuation.

-f

Ignores case when sorting.

-i

Ignores nonprinting characters.

-m

Merges already-sorted files. Does not sort.

-M

Assumes the first three letters of each line is a month abbreviation and then sorts by months.

-n

Sorts numerically.

-o filename

Sends output to the given file instead of standard output.

-r

Sorts in reverse order.

-u

Throws away duplicate lines.

strings

strings options files

Description

Searches for printable strings in a file or files and then outputs these strings.

Example

$ strings `which awk` | grep opyright
copyright
        -W copyright            --copyright
Copyright (C) 1989, 1991-%d Free Software Foundation.

Searches the awk command for the string opyright (short for copyright).

Options

Option

Usage

-n number

Searches for blocks of printable text with at least the given number of characters. Four is the default.

tr

tr options set1 set2

Description

Translates or deletes characters.

Example

$ cat /etc/passwd | tr ':' ' ' | tail −4
xfs x 43 43 X Font Server /etc/X11/fs /sbin/nologin
ntp x 38 38  /etc/ntp /sbin/nologin
gdm x 42 42  /var/gdm /sbin/nologin
ericfj x 500 500 Eric Foster-Johnson /home2/ericfj /bin/bash

Translates the colon in the /etc/passwd file to a space, for easier reading. Prints the last four lines.

Options

Option

Usage

-c

Complements. Uses all characters not in set1.

-d

Deletes all characters in set1.

-s

Squeezes the output by eliminating repeats.

Resolving Expressions

Shell scripts don't work that well with mathematical expressions. That's because the shells really treat most values as text strings. If you do need to resolve mathematical expressions, the following commands may help.

bc

bc options filenames

Description

Provides a programmable calculator. The bc command supports its own mini programming language. You can enter commands in the bc language at the command line or pipe the text of the commands to bc.

In bc, the basic data element is a number. You can then use math statements to modify numbers, or you can invoke functions. As a programming language, there are quite a few commands within bc.

Example

$ bc
bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
scale=2
x=10
x + 10
20
x
10
tax=100*7/100
tax
7.00
x = x + tax
x
17.00
print x
17.00
quit

Options

Option

Usage

-l

Loads the math library

-s

Runs bc in POSIX standard mode

expr

expr expression

Description

Evaluates an expression, usually a numeric expression. Note that expr works only with whole numbers (integers). For floating-point numbers, use bc.

Examples

$ expr 40 + 2
42

Adds 40 plus 2.

$ expr 40 / 10
4

Divides 40 by 10.

$ expr 42 % 10
2

Returns the remainder after dividing 42 by 10.

Options

None.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.28.9