Linux Commands By Examples

These are usually invoked by root and used for system maintenance or emergency filesystem repairs. Use with caution, as some of these commands may damage your system if misused.

Users and Groups

users

Show all logged on users. This is the approximate equivalent of who -q.

groups

Lists the current user and the groups she belongs to. This corresponds to the $GROUPS internal variable, but gives the group names, rather than the numbers.

bash$ groups
 
bozita cdrom cdwriter audio xgrp
 
bash$ echo $GROUPS
501

chown, chgrp

The chown command changes the ownership of a file or files. This command is a useful method that root can use to shift file ownership from one user to another. An ordinary user may not change the ownership of files, not even her own files.

root# chown bozo *.txt
 
              

The chgrp command changes the group ownership of a file or files. You must be owner of the file(s) as well as a member of the destination group (or root) to use this operation.

chgrp –recursive dunderheads *.data
#  The “dunderheads” group will now own all the “*.data” files
#+ all the way down the $PWD directory tree (that’s what “recursive” means).

useradd, userdel

The useradd administrative command adds a user account to the system and creates a home directory for that particular user, if so specified. The corresponding userdel command removes a user account from the system and deletes associated files.

NOTE

The adduser command is a synonym for useradd and is usually a symbolic link to it.

id

The id command lists the real and effective user IDs and the group IDs of the current user. This is the counterpart to the $UID, $EUID, and $GROUPS internal Bash variables.

bash$ id
 
uid=501(bozo) gid=501(bozo) groups=501(bozo),22(cdrom),80(cdwriter),81(audio)
 
bash$ echo $UID
501

who

Show all users logged on to the system.

bash$ who
bozo  tty1     Apr 27 17:45
 bozo  pts/0    Apr 27 17:46
 bozo  pts/1    Apr 27 17:47
 bozo  pts/2    Apr 27 17:49
 
              

The -m gives detailed information about only the current user. Passing any two arguments to who is the equivalent of who -m, as in who am i or who The Man.

bash$ who -m
 
localhost.localdomain!bozo  pts/2    Apr 27 17:49
              

whoami is similar to who -m, but only lists the user name.

bash$ whoami
bozo
              

w

Show all logged on users and the processes belonging to them. This is an extended version of who. The output of w may be piped to grep to find a specific user and/or process.

bash$ w | grep startx
bozo  tty1     -                 4:22pm  6:41   4.47s  0.45s  startx

logname

Show current user’s login name (as found in /var/run/utmp). This is a near-equivalent to whoami, above.

bash$ logname
 
bozo
 
bash$ whoami
bozo

However…

bash$ su
Password: ……
 
bash# whoami
 
root
bash# logname
bozo

su

Runs a program or script as a substitute user. su rjones starts a shell as user rjones. A naked su defaults to root.

sudo

Runs a command as root (or another user). This may be used in a script, thus permitting a regular user to run the script.

#!/bin/bash
 
# Some commands.
sudo cp /root/secretfile /home/bozo/secret
# Some more commands.

The file /etc/sudoers holds the names of users permitted to invoke sudo.

passwd

Sets or changes a user’s password.

The passwd can be used in a script, but should not be.

#!/bin/bash
#  set-new-password.sh: Not a good idea.
#  This script must be run as root,
#+ or better yet, not run at all.
 
ROOT_UID=0         # Root has $UID 0.
E_WRONG_USER=65    # Not root?
 
if [ “$UID” -ne “$ROOT_UID” ]
then
  echo; echo “Only root can run this script.”; echo
  exit $E_WRONG_USER
else
  echo; echo “You should know better than to run this script, root.”
fi  
 
 
username=bozo
NEWPASSWORD=security_violation
 
echo “$NEWPASSWORD” | passwd –stdin “$username”
#  The ‘–stdin’ option to ‘passwd’ permits
#+ getting new password from stdin (or a pipe).
 
echo; echo “User $username’s password changed!”
 
# Using the ‘passwd’ command in a script is dangerous.
 
exit 0

ac

Show users’ logged in time, as read from /var/log/wtmp. This is one of the GNU accounting utilities.

bash$ ac
        total       68.08

last

List last logged in users, as read from /var/log/wtmp. This command can also show remote logins.

newgrp

Change user’s group ID without logging out. This permits access to the new group’s files. Since users may be members of multiple groups simultaneously, this command finds little use.

Terminals

tty

Echoes the name of the current user’s terminal. Note that each separate xterm window counts as a different terminal.

bash$ tty
 
/dev/pts/1

stty

Shows and/or changes terminal settings. This complex command, used in a script, can control terminal behavior and the way output displays. See the info page, and study it carefully.

Example 13-1. setting an erase character

#!/bin/bash
# erase.sh: Using “stty” to set an erase character when reading input.
 
echo -n “What is your name? “
read name                      # Try to erase characters of input.
                               # Won’t work.
echo “Your name is $name.”
 
stty erase ‘#’                 # Set “hashmark” (#) as erase character.
echo -n “What is your name? “
read name                      # Use # to erase last character typed.
echo “Your name is $name.”
 
exit 0

Example 13-2. secret password: Turning off terminal echoing

#!/bin/bash
 
echo
echo -n “Enter password “
read passwd
echo “password is $passwd”
echo -n “If someone had been looking over your shoulder, “
echo “your password would have been compromised.”
 
echo && echo  # Two line-feeds in an “and list”.
 
stty -echo    # Turns off screen echo.
 
echo -n “Enter password again “
read passwd
echo
echo “password is $passwd”
echo
 
stty echo     # Restores screen echo.
 
exit 0

A creative use of stty is detecting a user keypress (without hitting ENTER).

Example 13-3. Keypress detection

#!/bin/bash
# keypress.sh: Detect a user keypress (”hot keyboard”).
 
echo
 
old_tty_settings=$(stty -g)   # Save old settings.
stty -icanon
Keypress=$(head -c1)          # or $(dd bs=1 count=1 2> /dev/null)
                              # on non-GNU systems
 
echo
echo “Key pressed was ”"$Keypress””.”
echo
 
stty “$old_tty_settings”      # Restore old settings.
 
# Thanks, Stephane Chazelas.
 
exit 0
terminals and modes Normally, a terminal works in the canonical mode. When a user hits a key, the resulting character does not immediately go to the program actually running in this terminal. A buffer local to the terminal stores keystrokes. When the user hits the ENTER key, this sends all the stored keystrokes to the program running. There is even a basic line editor inside the terminal.

bash$ stty -a
 
speed 9600 baud; rows 36; columns 96; line = 0;
 intr = ^C; quit = ^; erase = ^H; kill = ^U; eof = ^D; eol = ; eol2 = ;
 start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R; werase = ^W; lnext = ^V; flush = ^O;
 isig icanon iexten echo echoe echok -echonl -noflsh -xcase -tostop -echoprt
                

Using canonical mode, it is possible to redefine the special keys for the local terminal line editor.

bash$ cat > filexxx
whaIfoo barhello world
 
bash$ cat filexxx
hello world            
bash$ bash$ wc -c < file
13             
                

The process controlling the terminal receives only 13 characters (12 alphabetic ones, plus a newline), although the user hit 26 keys.

In non-canonical (“raw”) mode, every key hit (including special editing keys such as ctl-H) sends a character immediately to the controlling process.

The Bash prompt disables both icanon and echo, since it replaces the basic terminal line editor with its own more elaborate one. For example, when you hit ctl-A at the Bash prompt, there’s no ^A echoed by the terminal, but Bash gets a \1 character, interprets it, and moves the cursor to the begining of the line.

tset

Show or initialize terminal settings. This is a less capable version of stty.

bash$ tset -r
 
Terminal type is xterm-xfree86.
 Kill is control-U (^U).
 Interrupt is control-C (^C).
              

setserial

Set or display serial port parameters. This command must be run by root user and is usually found in a system setup script.

# From /etc/pcmcia/serial script:
 
IRQ=`setserial /dev/$DEVICE | sed -e ’s/.*IRQ: //’`
setserial /dev/$DEVICE irq 0 ; setserial /dev/$DEVICE irq $IRQ

getty, agetty

The initialization process for a terminal uses getty or agetty to set it up for login by a user. These commands are not used within user shell scripts. Their scripting counterpart is stty.

mesg

Enables or disables write access to the current user’s terminal. Disabling access would prevent another user on the network to write to the terminal.

TIP

It can be very annoying to have a message about ordering pizza suddenly appear in the middle of the text file you are editing. On a multi-user network, you might therefore wish to disable write access to your terminal when you need to avoid interruptions.

wall

This is an acronym for “write all”, i.e., sending a message to all users at every terminal logged into the network. It is primarily a system administrator’s tool, useful, for example, when warning everyone that the system will shortly go down due to a problem (see Example 17-2).

bash$ wall System going down for maintenance in 5 minutes!
 
Broadcast message from bozo (pts/1) Sun Jul  8 13:53:27 2001…
 
 System going down for maintenance in 5 minutes!
              

NOTE

If write access to a particular terminal has been disabled with mesg, then wall cannot send a message to it.

dmesg

Lists all system bootup messages to stdout. Handy for debugging and ascertaining which device drivers were installed and which system interrupts in use. The output of dmesg may, of course, be parsed with grep, sed, or awk from within a script.

bash$ dmesg | grep hda
 
Kernel command line: ro root=/dev/hda2
 hda: IBM-DLGA-23080, ATA DISK drive
 hda: 6015744 sectors (3080 MB) w/96KiB Cache, CHS=746/128/63
 hda: hda1 hda2 hda3 < hda5 hda6 hda7 > hda4
              

Information and Statistics

uname

Output system specifications (OS, kernel version, etc.) to stdout. Invoked with the -a option, gives verbose system info (see Example 12-4). The -s option shows only the OS type.

bash$ uname -a
Linux localhost.localdomain 2.2.15-2.5.0 #1 Sat Feb 5 00:13:43 EST 2000 i686 unknown
 
bash$ uname -s
Linux

arch

Show system architecture. Equivalent to uname -m. See Example 10-25.

bash$ arch
 
i686
 
bash$ uname -m
i686

lastcomm

Gives information about previous commands, as stored in the /var/account/pacct file. Command name and user name can be specified by options. This is one of the GNU accounting utilities.

lastlog

List the last login time of all system users. This references the /var/log/lastlog file.

bash$ lastlog
 
root          tty1                      Fri Dec  7 18:43:21 -0700 2001
 bin                                     **Never logged in**
 daemon                                  **Never logged in**
 bozo          tty1                      Sat Dec  8 21:14:29 -0700 2001
 
 
 
bash$ lastlog | grep root
root          tty1                      Fri Dec  7 18:43:21 -0700 2001
              

CAUTION

This command will fail if the user invoking it does not have read permission for the /var/log/lastlog file.

lsof

List open files. This command outputs a detailed table of all currently open files and gives information about their owner, size, the processes associated with them, and more. Of course, lsof may be piped to grep and/or awk to parse and analyze its results.

bash$ lsof
 
COMMAND    PID    USER   FD   TYPE     DEVICE    SIZE     NODE NAME
 init         1    root  mem    REG        3,5   30748    30303 /sbin/init
 init         1    root  mem    REG        3,5   73120     8069 /lib/ld-2.1.3.so
 init         1    root  mem    REG        3,5  931668     8075 /lib/libc-2.1.3.so
 cardmgr    213    root  mem    REG        3,5   36956    30357 /sbin/cardmgr
              

strace

Diagnostic and debugging tool for tracing system calls and signals. The simplest way of invoking it is strace COMMAND.

bash$ strace df
execve(”/bin/df”, [”df”], [/* 45 vars */]) = 0
 uname({sys=”Linux”, node=”bozo.localdomain”, …}) = 0
 brk(0)                                  = 0×804f5e4
            

This is the Linux equivalent of truss.

free

Shows memory and cache usage in tabular form. The output of this command lends itself to parsing, using grep, awk or Perl. The procinfo command shows all the information that free does, and much more.

bash$ free
 
                total       used       free     shared    buffers     cached
   Mem:         30504      28624       1880      15820       1608       16376
   -/+ buffers/cache:      10640      19864
   Swap:        68540       3128      65412

To show unused RAM memory:

bash$ free | grep Mem | awk ‘{ print $4 }’
1880

procinfo

Extract and list information and statistics from the /proc pseudo-filesystem. This gives a very extensive and detailed listing.

bash$ procinfo | grep Bootup
 
Bootup: Wed Mar 21 15:15:50 2001    Load average: 0.04 0.21 0.34 3/47 6829

lsdev

List devices, that is, show installed hardware.

bash$ lsdev
Device            DMA   IRQ  I/O Ports
 ————————————————
 cascade             4     2 
 dma                          0080-008f
 dma1                         0000-001f
 dma2                         00c0-00df
 fpu                          00f0-00ff
 ide0                     14  01f0-01f7 03f6-03f6
              

du

Show (disk) file usage, recursively. Defaults to current working directory, unless otherwise specified.

bash$ du -ach
 
1.0k    ./wi.sh
 1.0k    ./tst.sh
 1.0k    ./random.file
 6.0k    .
 6.0k    total

df

Shows filesystem usage in tabular form.

bash$ df
Filesystem           1k-blocks      Used Available Use% Mounted on
 /dev/hda5               273262     92607    166547  36% /
 /dev/hda8               222525    123951     87085  59% /home
 /dev/hda7              1408796   1075744    261488  80% /usr

stat

Gives detailed and verbose statistics on a given file (even a directory or device file) or set of files.

bash$ stat test.cru
  File: “test.cru”
   Size: 49970        Allocated Blocks: 100          Filetype: Regular File
   Mode: (0664/-rw-rw-r–)         Uid: (  501/ bozo)  Gid: (  501/ bozo)
 Device:  3,8   Inode: 18185     Links: 1    
 Access: Sat Jun  2 16:40:24 2001
 Modify: Sat Jun  2 16:40:24 2001
 Change: Sat Jun  2 16:40:24 2001
 
              

If the target file does not exist, stat returns an error message.

bash$ stat nonexistent-file
nonexistent-file: No such file or directory
              

vmstat

Display virtual memory statistics.

bash$ vmstat
 
   procs                      memory    swap          io system         cpu
 r  b  w   swpd   free   buff  cache  si  so    bi    bo   in    cs  us  sy id
 0  0  0      0  11040   2636  38952   0   0    33     7  271    88   8   3 89
            

netstat

Show current network statistics and information, such as routing tables and active connections. This utility accesses information in /proc/net.

netstat -r is equivalent to route.

uptime

Shows how long the system has been running, along with associated statistics.

bash$ uptime
 
10:28pm  up  1:57,  3 users,  load average: 0.17, 0.34, 0.27

hostname

Lists the system’s host name. This command sets the host name in an /etc/rc.d setup script (/etc/rc.d/rc.sysinit or similar). It is equivalent to uname -n, and a counterpart to the $HOSTNAME internal variable.

bash$ hostname
 
localhost.localdomain
 
bash$ echo $HOSTNAME
localhost.localdomain

hostid

Echo a 32-bit hexadecimal numerical identifier for the host machine.

bash$ hostid
7f0100

NOTE

This command allegedly fetches a “unique” serial number for a particular system. Certain product registration procedures use this number to brand a particular user license. Unfortunately, hostid only returns the machine network address in hexadecimal, with pairs of bytes transposed.The network address of a typical non-networked Linux machine, is found in /etc/hosts.

bash$ cat /etc/hosts
127.0.0.1               localhost.localdomain localhost

As it happens, transposing the bytes of 127.0.0.1, we get 0.127.1.0, which translates in hex to 007f0100, the exact equivalent of what hostid returns, above. There exist only a few million other Linux machines with this identical hostid.

sar

Invoking sar (system activity report) gives a very detailed rundown on system statistics. This command is found on some commercial UNIX systems, but is not part of the base Linux distribution. It is contained in the sysstat utilities package, written by Sebastien Godard.

bash$ sar
 
Linux 2.4.7-10 (localhost.localdomain)        12/31/2001
 
 10:30:01 AM       CPU     %user     %nice   %system     %idle
 10:40:00 AM       all      1.39      0.00      0.77     97.84
 10:50:00 AM       all     76.83      0.00      1.45     21.72
 11:00:00 AM       all      1.32      0.00      0.69     97.99
 11:10:00 AM       all      1.17      0.00      0.30     98.53
 11:20:00 AM       all      0.51      0.00      0.30     99.19
 06:30:00 PM       all    100.00      0.00    100.01      0.00
 Average:          all      1.39      0.00      0.66     97.95
           

readelf

Show information and statistics about a designated elf binary. This is part of the binutils package.

bash$ readelf -h /bin/bash
ELF Header:
   Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 
   Class:                             ELF32
   Data:                              2’s complement, little endian
   Version:                           1 (current)
   OS/ABI:                            UNIX - System V
   ABI Version:                       0
   Type:                              EXEC (Executable file)
   . . .

size

The size [/path/to/binary] command gives the segment sizes of a binary executable or archive file. This is mainly of use to programmers.

bash$ size /bin/bash
 
   text    data     bss     dec     hex filename
  495971   22496   17392  535859   82d33 /bin/bash
              

System Logs

logger

Appends a user-generated message to the system log (/var/log/messages). You do not have to be root to invoke logger.

logger Experiencing instability in network connection at 23:10, 05/21.
# Now, do a ‘tail /var/log/messages’.

By embedding a logger command in a script, it is possible to write debugging information to /var/log/messages.

logger -t $0 -i Logging at line “$LINENO”.
# The “-t” option specifies the tag for the logger entry.
# The “-i” option records the process ID.
 
# tail /var/log/message
# …
# Jul  7 20:48:58 localhost ./test.sh[1712]: Logging at line 3.

logrotate

This utility manages the system log files, rotating, compressing, deleting, and/or mailing them, as appropriate. Usually crond runs logrotate on a daily basis.

Adding an appropriate entry to /etc/logrotate.conf makes it possible to manage personal log files, as well as system-wide ones.

Job Control

ps

Process Statistics: lists currently executing processes by owner and PID (process id). This is usually invoked with ax options, and may be piped to grep or sed to search for a specific process.

bash$  ps ax | grep sendmail
295 ?      S      0:00 sendmail: accepting connections on port 25

pstree

Lists currently executing processes in “tree” format. The -p option shows the PIDs, as well as the process names.

top

Continuously updated display of most cpu-intensive processes. The -b option displays in text mode, so that the output may be parsed or accessed from a script.

bash$ top -b
 
  8:30pm  up 3 min,  3 users,  load average: 0.49, 0.32, 0.13
 45 processes: 44 sleeping, 1 running, 0 zombie, 0 stopped
 CPU states: 13.6% user,  7.3% system,  0.0% nice, 78.9% idle
 Mem:    78396K av,   65468K used,   12928K free,       0K shrd,    2352K buff
 Swap:  157208K av,       0K used,  157208K free                   37244K cached
 
   PID USER     PRI  NI  SIZE  RSS SHARE STAT %CPU %MEM   TIME COMMAND
   848 bozo      17   0   996  996   800 R     5.6  1.2   0:00 top
     1 root       8   0   512  512   444 S     0.0  0.6   0:04 init
     2 root       9   0     0    0     0 SW    0.0  0.0   0:00 keventd
              

nice

Run a background job with an altered priority. Priorities run from 19 (lowest) to -20 (highest). Only root may set the negative (higher) priorities. Related commands are renice, snice, and skill.

nohup

Keeps a command running even after user logs off. The command will run as a foreground process unless followed by &. If you use nohup within a script, consider coupling it with a wait to avoid creating an orphan or zombie process.

pidof

Identifies process id (pid) of a running job. Since job control commands, such as kill and renice act on the pid of a process (not its name), it is sometimes necessary to identify that pid. The pidof command is the approximate counterpart to the $PPID internal variable.

bash$ pidof xclock
880
              

Example 13-4. pidof helps kill a process

#!/bin/bash
# kill-process.sh
 
NOPROCESS=2
 
process=xxxyyyzzz  # Use nonexistent process.
# For demo purposes only…
# … don’t want to actually kill any actual process with this script.
#
# If, for example, you wanted to use this script to logoff the Internet,
#     process=pppd
 
t=`pidof $process`       # Find pid (process id) of $process.
# The pid is needed by ‘kill’ (can’t ‘kill’ by program name).
 
if [ -z “$t” ]           # If process not present, ‘pidof’ returns null.
then
  echo “Process $process was not running.”
  echo “Nothing killed.”
  exit $NOPROCESS
fi  
 
kill $t                  # May need ‘kill -9′ for stubborn process.
 
# Need a check here to see if process allowed itself to be killed.
# Perhaps another ” t=`pidof $process` “.
 
 
# This entire script could be replaced by
#    kill $(pidof -x process_name)
# but it would not be as instructive.
 
exit 0

fuser

Identifies the processes (by pid) that are accessing a given file, set of files, or directory. May also be invoked with the -k option, which kills those processes. This has interesting implications for system security, especially in scripts preventing unauthorized users from accessing system services.

crond

Administrative program scheduler, performing such duties as cleaning up and deleting system log files and updating the slocate database. This is the superuser version of at (although each user may have their own crontab file which can be changed with the crontab command). It runs as a daemon and executes scheduled entries from /etc/crontab.

Process Control and Booting

init

The init command is the parent of all processes. Called in the final step of a bootup, init determines the runlevel of the system from /etc/inittab. Invoked by its alias telinit, and by root only.

telinit

Symlinked to init