The startup and shutdown scripts in
Show all logged on users. This is the approximate equivalent of who -q.
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.
|
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. [1]
|
The chgrp command changes the
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). |
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 [2] and deletes associated files.
![]() | The adduser command is a synonym for useradd and is usually a symbolic link to it. |
Modify a user account. Changes may be made to the password, group membership, expiration date, and other attributes of a given user's account. With this command, a user's password may be locked, which has the effect of disabling the account.
Modify a given group. The group name and/or ID number may be changed using this command.
The id command lists the real and effective user IDs and the group IDs of the user associated with the current process. This is the counterpart to the $UID, $EUID, and $GROUPS internal Bash variables.
|
![]() | The id command shows the effective IDs only when they differ from the real ones. |
Also see Example 9-5.
Show all users logged on to the system.
|
The
|
whoami is similar to who -m, but only lists the user name.
|
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.
|
Show current user's login name (as found in
|
However . . .
|
![]() | While logname prints the name of the logged in user, whoami gives the name of the user attached to the current process. As we have just seen, sometimes these are not the same. |
Runs a program or script as a substitute user. su rjones starts a shell as user rjones. A naked su defaults to root. See Example A-15.
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
Sets, changes, or manages a user's password.
The passwd command can be used in a script, but probably should not be.
Example 16-1. Setting a new password
#!/bin/bash # setnew-password.sh: For demonstration purposes only. # Not a good idea to actually run this script. # This script must be run as root. ROOT_UID=0 # Root has $UID 0. E_WRONG_USER=65 # Not root? E_NOSUCHUSER=70 SUCCESS=0 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." echo "Even root users get the blues... " echo fi username=bozo NEWPASSWORD=security_violation # Check if bozo lives here. grep -q "$username" /etc/passwd if [ $? -ne $SUCCESS ] then echo "User $username does not exist." echo "No password changed." exit $E_NOSUCHUSER fi echo "$NEWPASSWORD" | passwd --stdin "$username" # The '--stdin' option to 'passwd' permits #+ getting a 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 |
The passwd command's
Show users' logged in time, as read from
|
List last logged in users, as read from
For example, to show the last few times the system rebooted:
|
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 only limited use.
![]() | Kurt Glaesemann points out that the newgrp command could prove helpful in setting the default group permissions for files a user writes. However, the chgrp command might be more convenient for this purpose. |
Echoes the name (filename) of the current user's terminal. Note that each separate xterm window counts as a different terminal.
|
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 16-2. 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 backspace
#+ to erase characters of input.
# Problems?
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
# Even after the script exits, the new key value remains set.
# Exercise: How would you reset the erase character to the default value? |
Example 16-3. secret password: Turning off terminal echoing
#!/bin/bash # secret-pw.sh: secret password 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 # Do an 'info stty' for more on this useful-but-tricky command. |
A creative use of stty is detecting a user keypress (without hitting ENTER).
Example 16-4. Keypress detection
#!/bin/bash
# keypress.sh: Detect a user keypress ("hot keys").
echo
old_tty_settings=$(stty -g) # Save old settings (why?).
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 |
Also see Example 9-3.
Set certain terminal attributes. This command writes
to its terminal's
|
The setterm command can be used within a
script to change the appearance of text written to
setterm -bold on echo bold hello setterm -bold off echo normal hello |
Show or initialize terminal settings. This is a less capable version of stty.
|
Set or display serial port parameters. This command must be run by root 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 |
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.
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.
![]() | It can be quite 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. |
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 18-1).
|
![]() | If write access to a particular terminal has been disabled with mesg, then wall cannot send a message to that terminal. |
Output system specifications (OS, kernel version,
etc.) to
|
Show system architecture. Equivalent to uname -m. See Example 10-26.
|
Gives information about previous commands, as stored
in the
List the last login time of all system users. This
references the
|
![]() | This command will fail if the user invoking
it does not have read permission for the
|
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.
|
The lsof command is a useful,
if complex administrative tool. If you are unable to
dismount a filesystem and get an error message that it is
still in use, then running lsof helps
determine which files are still open on that filesystem. The
|
System trace: diagnostic and debugging tool for tracing system calls and signals. This command and ltrace, following, are useful for diagnosing why a given program or package fails to run . . . perhaps due to missing libraries or related causes.
|
This is the Linux equivalent of the Solaris truss command.
Library trace: diagnostic and debugging tool that traces library calls invoked by a given command.
|
Network mapper and port scanner. This command scans a server to locate open ports and the services associated with those ports. It can also report information about packet filters and firewalls. This is an important security tool for locking down a network against hacking attempts.
#!/bin/bash SERVER=$HOST # localhost.localdomain (127.0.0.1). PORT_NUMBER=25 # SMTP port. nmap $SERVER | grep -w "$PORT_NUMBER" # Is that particular port open? # grep -w matches whole words only, #+ so this wouldn't match port 1025, for example. exit 0 # 25/tcp open smtp |
The nc (netcat) utility is a complete toolkit for connecting to and listening to TCP and UDP ports. It is useful as a diagnostic and testing tool and as a component in simple script-based HTTP clients and servers.
|
Example 16-5. Checking a remote server for identd
#! /bin/sh
## Duplicate DaveG's ident-scan thingie using netcat. Oooh, he'll be p*ssed.
## Args: target port [port port port ...]
## Hose stdout _and_ stderr together.
##
## Advantages: runs slower than ident-scan, giving remote inetd less cause
##+ for alarm, and only hits the few known daemon ports you specify.
## Disadvantages: requires numeric-only port args, the output sleazitude,
##+ and won't work for r-services when coming from high source ports.
# Script author: Hobbit <hobbit@avian.org>
# Used in ABS Guide with permission.
# ---------------------------------------------------
E_BADARGS=65 # Need at least two args.
TWO_WINKS=2 # How long to sleep.
THREE_WINKS=3
IDPORT=113 # Authentication "tap ident" port.
RAND1=999
RAND2=31337
TIMEOUT0=9
TIMEOUT1=8
TIMEOUT2=4
# ---------------------------------------------------
case "${2}" in
"" ) echo "Need HOST and at least one PORT." ; exit $E_BADARGS ;;
esac
# Ping 'em once and see if they *are* running identd.
nc -z -w $TIMEOUT0 "$1" $IDPORT || \
{ echo "Oops, $1 isn't running identd." ; exit 0 ; }
# -z scans for listening daemons.
# -w $TIMEOUT = How long to try to connect.
# Generate a randomish base port.
RP=`expr $$ % $RAND1 + $RAND2`
TRG="$1"
shift
while test "$1" ; do
nc -v -w $TIMEOUT1 -p ${RP} "$TRG" ${1} < /dev/null > /dev/null &
PROC=$!
sleep $THREE_WINKS
echo "${1},${RP}" | nc -w $TIMEOUT2 -r "$TRG" $IDPORT 2>&1
sleep $TWO_WINKS
# Does this look like a lamer script or what . . . ?
# ABS Guide author comments: "Ain't really all that bad . . .
#+ kinda clever, actually."
kill -HUP $PROC
RP=`expr ${RP} + 1`
shift
done
exit $?
# Notes:
# -----
# Try commenting out line 30 and running this script
#+ with "localhost.localdomain 25" as arguments.
# For more of Hobbit's 'nc' example scripts,
#+ look in the documentation:
#+ the /usr/share/doc/nc-X.XX/scripts directory. |
And, of course, there's Dr. Andrew Tridgell's notorious one-line script in the BitKeeper Affair:
echo clone | nc thunk.org 5000 > e2fsprogs.dat |
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.
|
To show unused RAM memory:
|
Extract and list information and statistics from the
|
List devices, that is, show installed hardware.
|
Show (disk) file usage, recursively. Defaults to current working directory, unless otherwise specified.
|
Shows filesystem usage in tabular form.
|
Lists all system bootup messages to
|
Gives detailed and verbose statistics on a given file (even a directory or device file) or set of files.
|
If the target file does not exist, stat returns an error message.
|
In a script, you can use stat to extract information about files (and filesystems) and set variables accordingly.
#!/bin/bash # fileinfo2.sh # Per suggestion of Joël Bourquard and . . . # http://www.linuxquestions.org/questions/showthread.php?t=410766 FILENAME=testfile.txt file_name=$(stat -c%n "$FILENAME") # Same as "$FILENAME" of course. file_owner=$(stat -c%U "$FILENAME") file_size=$(stat -c%s "$FILENAME") # Certainly easier than using "ls -l $FILENAME" #+ and then parsing with sed. file_inode=$(stat -c%i "$FILENAME") file_type=$(stat -c%F "$FILENAME") file_access_rights=$(stat -c%A "$FILENAME") echo "File name: $file_name" echo "File owner: $file_owner" echo "File size: $file_size" echo "File inode: $file_inode" echo "File type: $file_type" echo "File access rights: $file_access_rights" exit 0 sh fileinfo2.sh File name: testfile.txt File owner: bozo File size: 418 File inode: 1730378 File type: regular file File access rights: -rw-rw-r-- |
Display virtual memory statistics.
|
Show current network statistics and information,
such as routing tables and active connections. This utility
accesses information in
netstat -r is equivalent to route.
|
![]() | A netstat -lptu shows sockets that are listening to ports, and the associated processes. This can be useful for determining whether a computer has been hacked or compromised. |
Shows how long the system has been running, along with associated statistics.
|
![]() | A load average of 1 or less indicates that the system handles processes immediately. A load average greater than 1 means that processes are being queued. When the load average gets above 3, then system performance is significantly degraded. |
Lists the system's host name. This command sets the host
name in an
|
Similar to the hostname command are the domainname, dnsdomainname, nisdomainname, and ypdomainname commands. Use these to display or set the system DNS or NIS/YP domain name. Various options to hostname also perform these functions.
Echo a 32-bit hexadecimal numerical identifier for the host machine.
|
![]() | 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
As it happens, transposing the bytes of
|
Invoking sar (System Activity Reporter) gives a very detailed rundown on system statistics. The Santa Cruz Operation ("Old" SCO) released sar as Open Source in June, 1999.
This command is not part of the base Linux distribution, but may be obtained as part of the sysstat utilities package, written by Sebastien Godard.
|
Show information and statistics about a designated elf binary. This is part of the binutils package.
|
The size [/path/to/binary] command gives the segment sizes of a binary executable or archive file. This is mainly of use to programmers.
|
Appends a user-generated message to the system log
(
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
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. |
This utility manages the system log files, rotating,
compressing, deleting, and/or e-mailing them, as appropriate.
This keeps the
Adding an appropriate entry to
![]() | Stefano Falsetto has created rottlog, which he considers to be an improved version of logrotate. |
|
To display system processes in graphical "tree" format: ps afjx or ps ax --forest.
Combining the ps command with grep or kill.
|
Compare the action of pkill with killall.
Lists currently executing processes in
"tree" format. The
Continuously updated display of most cpu-intensive
processes. The
|
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 and snice, which change the priority of a running process or processes, and skill, which sends a kill signal to a process or processes.
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.
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.
|
Example 16-6. 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` " or ... # This entire script could be replaced by # kill $(pidof -x process_name) # or # killall process_name # but it would not be as instructive. exit 0 |
Identifies the processes (by PID) that are accessing
a given file, set of files, or directory. May also be
invoked with the
|
One important application for fuser is when physically inserting or removing storage media, such as CD ROM disks or USB flash drives. Sometimes trying a umount fails with a device is busy error message. This means that some user(s) and/or process(es) are accessing the device. An fuser -um /dev/device_name will clear up the mystery, so you can kill any relevant processes.
|
The fuser command, invoked with the
|
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
![]() | Some flavors of Linux run crond, Matthew Dillon's version of cron. |
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
Symlinked to init, this is a means of changing the system runlevel, usually done for system maintenance or emergency filesystem repairs. Invoked only by root. This command can be dangerous -- be certain you understand it well before using!
Shows the current and last runlevel, that is, whether the system
is halted (runlevel
Command set to shut the system down, usually just prior to a power down.
Starts or stops a system service.
The startup scripts in
|
Network interface configuration and tuning utility.
|
The ifconfig command is most often used at bootup to set up the interfaces, or to shut them down when rebooting.
# Code snippets from /etc/rc.d/init.d/network
# ...
# Check that networking is up.
[ ${NETWORKING} = "no" ] && exit 0
[ -x /sbin/ifconfig ] || exit 0
# ...
for i in $interfaces ; do
if ifconfig $i 2>/dev/null | grep -q "UP" >/dev/null 2>&1 ; then
action "Shutting down interface $i: " ./ifdown $i boot
fi
# The GNU-specific "-q" option to "grep" means "quiet", i.e.,
#+ producing no output.
# Redirecting output to /dev/null is therefore not strictly necessary.
# ...
echo "Currently active devices:"
echo `/sbin/ifconfig | grep ^[a-z] | awk '{print $1}'`
# ^^^^^ should be quoted to prevent globbing.
# The following also work.
# echo $(/sbin/ifconfig | awk '/^[a-z]/ { print $1 })'
# echo $(/sbin/ifconfig | sed -e 's/ .*//')
# Thanks, S.C., for additional comments. |
See also Example 29-6.
This is the command set for configuring a wireless network. It is the wireless equivalent of ifconfig, above.
General purpose utility for setting up, changing, and analyzing IP (Internet Protocol) networks and attached devices. This command is part of the iproute2 package.
|
Or, in a script:
#!/bin/bash # Script by Juan Nicolas Ruiz # Used with his kind permission. # Setting up (and stopping) a GRE tunnel. # --- start-tunnel.sh --- LOCAL_IP="192.168.1.17" REMOTE_IP="10.0.5.33" OTHER_IFACE="192.168.0.100" REMOTE_NET="192.168.3.0/24" /sbin/ip tunnel add netb mode gre remote $REMOTE_IP \ local $LOCAL_IP ttl 255 /sbin/ip addr add $OTHER_IFACE dev netb /sbin/ip link set netb up /sbin/ip route add $REMOTE_NET dev netb exit 0 ############################################# # --- stop-tunnel.sh --- REMOTE_NET="192.168.3.0/24" /sbin/ip route del $REMOTE_NET dev netb /sbin/ip link set netb down /sbin/ip tunnel del netb exit 0 |
Show info about or make changes to the kernel routing table.
|
Check network and system configuration. This command
lists and
manages the network and system services started at bootup in
the
Originally a port from IRIX to Red Hat Linux, chkconfig may not be part of the core installation of some Linux flavors.
|
Network packet "sniffer." This is a tool for analyzing and troubleshooting traffic on a network by dumping packet headers that match specified criteria.
Dump ip packet traffic between hosts bozoville and caduceus:
|
Of course, the output of tcpdump can be parsed with certain of the previously discussed text processing utilities.
Mount a filesystem, usually on an external device,
such as a floppy or CDROM. The file
mount -a mounts all filesystems and
partitions listed in
mount -t iso9660 /dev/cdrom /mnt/cdrom # Mounts CD ROM. ISO 9660 is a standard CD ROM filesystem. mount /mnt/cdrom # Shortcut, if /mnt/cdrom listed in /etc/fstab |
The versatile mount command can even mount an ordinary file on a block device, and the file will act as if it were a filesystem. Mount accomplishes that by associating the file with a loopback device. One application of this is to mount and examine an ISO9660 filesystem image before burning it onto a CDR. [3]
Example 16-7. Checking a CD image
# As root...
mkdir /mnt/cdtest # Prepare a mount point, if not already there.
mount -r -t iso9660 -o loop cd-image.iso /mnt/cdtest # Mount the image.
# "-o loop" option equivalent to "losetup /dev/loop0"
cd /mnt/cdtest # Now, check the image.
ls -alR # List the files in the directory tree there.
# And so forth. |
Unmount a currently mounted filesystem. Before physically removing a previously mounted floppy or CDROM disk, the device must be umounted, else filesystem corruption may result.
umount /mnt/cdrom # You may now press the eject button and safely remove the disk. |
![]() | The automount utility, if properly installed, can mount and unmount floppies or CDROM disks as they are accessed or removed. On "multispindle" laptops with swappable floppy and optical drives, this can cause problems, however. |
The newer Linux distros have deprecated
mount and umount.
The successor, for command-line mounting of removable storage
devices, is gnome-mount. It can take the
For example, to mount a USB flash drive:
|
Forces an immediate write of all updated data from
buffers to hard drive (synchronize drive
with buffers). While not strictly necessary, a
sync assures the sys admin or
user that the data just changed will survive a sudden
power failure. In the olden days, a
At times, you may wish to force an immediate buffer flush, as when securely deleting a file (see Example 15-60) or when the lights begin to flicker.
Sets up and configures loopback devices.
Creates a swap partition or file. The swap area must subsequently be enabled with swapon.
Enable / disable swap partitition or file. These commands usually take effect at bootup and shutdown.
Create a Linux ext2 filesystem. This command must be invoked as root.
Example 16-9. Adding a new hard drive
#!/bin/bash # Adding a second hard drive to system. # Software configuration. Assumes hardware already mounted. # From an article by the author of this document. # In issue #38 of "Linux Gazette", http://www.linuxgazette.com. ROOT_UID=0 # This script must be run as root. E_NOTROOT=67 # Non-root exit error. if [ "$UID" -ne "$ROOT_UID" ] then echo "Must be root to run this script." exit $E_NOTROOT fi # Use with extreme caution! # If something goes wrong, you may wipe out your current filesystem. NEWDISK=/dev/hdb # Assumes /dev/hdb vacant. Check! MOUNTPOINT=/mnt/newdisk # Or choose another mount point. fdisk $NEWDISK mke2fs -cv $NEWDISK1 # Check for bad blocks & verbose output. # Note: /dev/hdb1, *not* /dev/hdb! mkdir $MOUNTPOINT chmod 777 $MOUNTPOINT # Makes new drive accessible to all users. # Now, test... # mount -t ext2 /dev/hdb1 /mnt/newdisk # Try creating a directory. # If it works, umount it, and proceed. # Final step: # Add the following line to /etc/fstab. # /dev/hdb1 /mnt/newdisk ext2 defaults 1 1 exit |
See also Example 16-8 and Example 28-3.
Tune ext2 filesystem. May be used to change filesystem parameters, such as maximum mount count. This must be invoked as root.
![]() | This is an extremely dangerous command. Use it at your own risk, as you may inadvertently destroy your filesystem. |
Dump (list to
|
List or change hard disk parameters. This command must be invoked as root, and it may be dangerous if misused.
Create or change a partition table on a storage device, usually a hard drive. This command must be invoked as root.
![]() | Use this command with extreme caution. If something goes wrong, you may destroy an existing filesystem. |
Filesystem check, repair, and debug command set.
fsck: a front end for checking a UNIX filesystem (may invoke other utilities). The actual filesystem type generally defaults to ext2.
e2fsck: ext2 filesystem checker.
debugfs: ext2 filesystem debugger. One of the uses of this versatile, but dangerous command is to (attempt to) recover deleted files. For advanced users only!
![]() | All of these should be invoked as root, and they can damage or destroy a filesystem if misused. |
Checks for bad blocks (physical media flaws) on a storage device. This command finds use when formatting a newly installed hard drive or testing the integrity of backup media. [4] As an example, badblocks /dev/fd0 tests a floppy disk.
The badblocks command may be invoked destructively (overwrite all data) or in non-destructive read-only mode. If root user owns the device to be tested, as is generally the case, then root must invoke this command.
The lsusb command lists all USB (Universal Serial Bus) buses and the devices hooked up to them.
The usbmodules command outputs information about the driver modules for connected USB devices.
|
Lists pci busses present.
|
Creates a boot floppy which can be used to bring up the
system if, for example, the MBR (master boot record) becomes
corrupted. Of special interest is the
The mkbootdisk command is actually
a Bash script, written by Erik Troan, in the
Creates an ISO9660 filesystem suitable for a CDR image.
CHange ROOT directory. Normally commands are fetched
from $PATH, relative to
A
The chroot command is also handy
when running from an emergency boot floppy
(chroot to
![]() | It might be necessary to copy certain system
files to a chrooted directory,
since the normal |
This utility is part of the procmail package (www.procmail.org). It creates a lock file, a semaphore [5] file that controls access to a file, device, or resource. The lock file serves as a flag that this particular file, device, or resource is in use by a process (it is "busy"), and this permits only restricted access (or no access) to other processes.
lockfile /home/bozo/lockfiles/$0.lock
# Creates a write-protected lockfile prefixed with the name of the script.
lockfile /home/bozo/lockfiles/${0##*/}.lock
# A safer version of the above, as pointed out by E. Choroba. |
Lock files are used in such applications as protecting system mail folders from simultaneously being changed by multiple users, indicating that a modem port is being accessed, and showing that an instance of Netscape is using its cache. Scripts may check for the existence of a lock file created by a certain process to check if that process is running. Note that if a script attempts to create a lock file that already exists, the script will likely hang.
Normally, applications create and check for lock files
in the
appname=xyzip
# Application "xyzip" created lock file "/var/lock/xyzip.lock".
if [ -e "/var/lock/$appname.lock" ]
then #+ Prevent other programs & scripts
# from accessing files/resources used by xyzip.
... |
Much less useful than the lockfile command is flock. It sets an "advisory" lock on a file and then executes a command while the lock is on. This is to prevent any other process from setting a lock on that file until completion of the specified command.
flock $0 cat $0 > lockfile__$0 # Set a lock on the script the above line appears in, #+ while listing the script to stdout. |
![]() | Unlike lockfile, flock does not automatically create a lock file. |
Creates block or character device files (may be necessary when installing new hardware on the system). The MAKEDEV utility has virtually all of the functionality of mknod, and is easier to use.
Utility for creating device files. It must be run as
root, and in the
Automatically deletes files which have not been accessed within a specified period of time. Usually invoked by cron to remove stale log files.
The dump command is an elaborate filesystem backup utility, generally used on larger installations and networks. [7] It reads raw disk partitions and writes a backup file in a binary format. Files to be backed up may be saved to a variety of storage media, including disks and tape drives. The restore command restores backups made with dump.
Perform a low-level format on a floppy disk
(
Sets an upper limit on use
of system resources. Usually invoked with the
![]() | Judicious use of ulimit can protect a system against the dreaded fork bomb.
A ulimit -Hu XX (where
XX is the user process limit) in
|
Display user or group disk quotas.
Set user or group disk quotas from the command line.
User file creation permissions
mask. Limit the default file
attributes for a particular user. All files created
by that user take on the attributes specified by
umask. The (octal) value passed to
umask defines the file permissions
disabled. For example, umask
022 ensures that new files will have at most
755 permissions (777 NAND 022).
[8]
Of course, the user may later change the
attributes of particular files with chmod. The usual practice
is to set the value of umask
in
Example 16-10. Using umask to hide an output file from prying eyes
#!/bin/bash
# rot13a.sh: Same as "rot13.sh" script, but writes output to "secure" file.
# Usage: ./rot13a.sh filename
# or ./rot13a.sh <filename
# or ./rot13a.sh and supply keyboard input (stdin)
umask 177 # File creation mask.
# Files created by this script
#+ will have 600 permissions.
OUTFILE=decrypted.txt # Results output to file "decrypted.txt"
#+ which can only be read/written
# by invoker of script (or root).
cat "$@" | tr 'a-zA-Z' 'n-za-mN-ZA-M' > $OUTFILE
# ^^ Input from stdin or a file. ^^^^^^^^^^ Output redirected to file.
exit 0 |
Get info about or make changes to root device, swap space, or video mode. The functionality of rdev has generally been taken over by lilo, but rdev remains useful for setting up a ram disk. This is a dangerous command, if misused.
List installed kernel modules.
|
![]() | Doing a cat /proc/modules gives the same information. |
Force installation of a kernel module (use modprobe instead, when possible). Must be invoked as root.
Force unloading of a kernel module. Must be invoked as root.
Module loader that is normally invoked automatically in a startup script. Must be invoked as root.
Creates module dependency file. Usually invoked from a startup script.
Output information about a loadable module.
|
Runs a program or script with certain environmental variables
set or changed (without changing the overall system
environment). The
![]() | The first line of a script (the "sha-bang" line) may use env when the path to the shell or interpreter is unknown.
Or even ...
|
Show shared lib dependencies for an executable file.
|
Run a command repeatedly, at specified time intervals.
The default is two-second intervals, but this may be changed
with the
watch -n 5 tail /var/log/messages # Shows tail end of system log, /var/log/messages, every five seconds. |
Remove the debugging symbolic references from an executable binary. This decreases its size, but makes debugging it impossible.
This command often occurs in a Makefile, but rarely in a shell script.
List symbols in an unstripped compiled binary.
Remote distribution client: synchronizes, clones, or backs up a file system on a remote server.
| [1] | This is the case on a Linux machine or a UNIX system with disk quotas. | |
| [2] | The userdel command will fail if the particular user being deleted is still logged on. | |
| [3] | For more detail on burning CDRs, see Alex Withers' article, Creating CDs, in the October, 1999 issue of Linux Journal. | |
| [4] | The | |
| [5] | Definition: A semaphore is a flag or signal. (The usage originated in railroading, where a colored flag, lantern, or striped movable arm semaphore indicated whether a particular track was in use and therefore unavailable for another train.) A UNIX process can check the appropriate semaphore to determine whether a particular resource is available/accessible. | |
| [6] | Since only root
has write permission in the | |
| [7] | Operators of single-user Linux systems generally prefer something simpler for backups, such as tar. | |
| [8] | NAND is the logical not-and operator. Its effect is somewhat similar to subtraction. | |
| [9] | In Bash and other Bourne shell derivatives, it is possible to set variables in a single command's environment.
|