Advanced Bash-Scripting HOWTO: A guide to shell scripting, using Bash | ||
---|---|---|
Prev | Chapter 3. Tutorial / Reference | Next |
The startup and shutdown scripts in /etc/rc.d illustrate the uses (and usefulness) of these comands. 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.
Output system specifications (OS, kernel version, etc.) to stdout. Invoked with the -a option, gives verbose system info (see Example 3-48).
bash$ uname -a Linux localhost.localdomain 2.2.15-2.5.0 #1 Sat Feb 5 00:13:43 EST 2000 i686 unknown |
Show system architecture. Equivalent to uname -m.
bash$ arch i686 |
bash$ uname -m i686 |
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 (see Section 3.7).
bash$ id uid=501(bozo) gid=501(bozo) groups=501(bozo),22(cdrom),80(cdwriter),81(audio) |
bash$ echo $UID 501 |
Show all users logged on to the system.
whoami is a variant of who that lists only the current user.
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 grendel tty1 - 4:22pm 6:41 4.47s 0.45s startx |
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.
bash$ groups bozita cdrom cdwriter audio xgrp |
bash$ echo $GROUPS 501 |
Lists the system's host name, as recorded in /etc/hosts. This is a counterpart to the $HOSTNAME internal variable.
bash$ hostname localhost.localdomain |
bash$ echo $HOSTNAME localhost.localdomain |
Sets an upper limit on system resources. Usually invoked with the -f option, which sets a limit on file size (ulimit -f 1000 limits files to 1 meg maximum). The -t option limits the coredump size (ulimit -c 0 eliminates coredumps). Normally, the value of ulimit would be set in /etc/profile and/or ~/.bash_profile (see Section 3.23).
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 |
Runs a program or script with certain environmental variables set or changed (without changing the overall system environment). The [varname=xxx] permits changing the environmental variable varname for the duration of the script. With no options specified, this command lists all the environmental variable settings.
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-7.
This command permits changing shell options on the fly (see Example 3-85). It often appears in the Bash setup files, but also has its uses in scripts. Works with version 2 of Bash only.
1 shopt -s cdspell 2 # Allows minor misspelling directory names with 'cd' 3 command. |
This utility is part of the procmail package (www.procmail.org). It creates a lock file, a semaphore 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 particular process ("busy"), and permitting only restricted access (or no access) to other processes. 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 create a lock file that already exists, the script will likely hang.
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. It runs as a daemon (background process) and executes scheduled entries from /etc/crontab.
CHange ROOT directory. Normally commands are fetched from $PATH, relative to /, the default root directory. This changes the root directory to a different one (and also changes the working directory to there). A chroot /opt would cause references to /usr/bin to be translated to /opt/usr/bin, for example. This is useful for security purposes, for instance when the system administrator wishes to restrict certain users, such as those telnetting in, to a secured portion of the filesystem. Note that after a chroot, the execution path for system binaries is no longer valid.
The chroot command is also handy when running from an emergency boot floppy (chroot to /dev/fd0), or as an option to lilo when recovering from a system crash. Other uses include installation from a different filesystem (an rpm option). Invoke only as root, and use with caution.
User file creation 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 the file permissions disabled. For example, umask 022 ensures that new files will have at most 755 permissions (777 NAND 022). [1] 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 /etc/profile and/or ~/.bash_profile (see Section 3.23).
Show shared lib dependencies for an executable file.
bash$ ldd /bin/ls libc.so.6 => /lib/libc.so.6 (0x4000c000) /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x80000000) |
Show current user's login name (as found in /var/run/utmp). This is equivalent to whoami, above.
bash$ logname bozo |
bash$ whoami bozo |
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 |
Shows and/or changes terminal settings.
Example 3-68. secret password: Turning off terminal echoing
1 #!/bin/bash 2 3 echo 4 echo -n "Enter password " 5 read passwd 6 echo "password is $passwd" 7 echo -n "If someone had been looking over your shoulder, " 8 echo "your password would have been compromised." 9 10 echo && echo # Two line-feeds in an "and list". 11 12 stty -echo # Turns off screen echo. 13 14 echo -n "Enter password again " 15 read passwd 16 echo 17 echo "password is $passwd" 18 echo 19 20 stty echo # Restores screen echo. 21 22 exit 0 |
This is an acronym for "write all", i.e., sending a message to all users every terminal logged on in 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 3-94).
wall System going down for maintenance in 5 minutes! |
Appends a user-generated message to the system log (/var/log/messages). You do not have to be root to invoke logger.
1 logger Experiencing instability in network connection at 23:10, 05/21. 2 # Now, do a 'tail /var/log/messages'. |
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.
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.
Identifies process id (pid) of a running job. Job control commands, such as kill and renice act on the pid of a process, rather than its name. This is the counterpart of the $PPID internal variable (see Section 3.7).
Example 3-69. pidof helps kill a process
1 #!/bin/bash 2 # kill-process 3 4 NOPROCESS=2 5 6 process=xxxyyyzzz # Use nonexistent process. 7 # For demo purposes only... 8 # ... don't want to actually kill any actual process with this script. 9 # If, for example, you wanted to use this script to logoff the Internet process=pppd 10 11 t=`pidof $process` # Find pid (process id) of $process. 12 # The pid is needed by 'kill' (can't 'kill' by program name). 13 14 if [ -z $t ] # If process not present, 'pidof' returns null. 15 then 16 echo "Process $process was not running." 17 echo "Nothing killed." 18 exit $NOPROCESS 19 fi 20 21 kill $t # May need 'kill -9' for stubborn process. 22 23 # Need a check here to see if process allowed itself to be killed. 24 # Perhaps another " t=`pidof $process` ". 25 26 exit 0 |
Show or change the priority of a background job. Priorities run from 19 (lowest) to -20 (highest). Only root may set the negative (higher) priorities. Related commands are renice, snice, and skill.
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.
Shows memory and cache usage in tabular form. The output of this command lends itself to parsing, using grep, awk or Perl.
bash$ free total used free shared buffers cached Mem: 30504 28624 1880 15820 1608 16376 -/+ buffers/cache: 10640 19864 Swap: 68540 3128 65412 |
Forces an immediate write of all updated data from buffers to hard drive. 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 sync sync was a useful precautionary measure before a system reboot.
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.
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 0), in single-user mode (1), in multi-user mode (2 or 3), in X Windows (5), or rebooting (6).
Command set to shut the system down, usually just prior to a power down.
This is actually a system call that replaces the current process with a specified command. It is mostly seen in combination with find, to execute a command on the files found (see Example 3-47). When used as a standalone in a script, it forces an exit from the script when the exec'ed command terminates. An exec is also used to reassign file descriptors. exec <zzz-file replaces stdin with the file zzz-file (see Example 3-72).
Network interface configuration utility.
Show info about or make changes to the kernel routing table.
Show current network information and statistics, such as routing tables and active connections.
Creates block or character device files (may be necessary when installing new hardware on the system).
Mount a filesystem, usually on an external device, such as a floppy or CDROM. The file /etc/fstab provides a handy listing of available filesystems, including options, that may be automatically or manually mounted. The file /etc/mtab shows the currently mounted filesystems (including the virtual ones, such as /proc).
1 mount -t iso9660 /dev/cdrom /mnt/cdrom 2 # Mounts CDROM 3 mount /mnt/cdrom 4 # Shortcut, if /mnt/cdrom listed in /etc/fstab |
Unmount a currently mounted filesystem. Before physically removing a previously mounted floppy or CDROM disk, the device must be umount'ed, else filesystem corruption may result.
1 umount /mnt/cdrom |
List installed kernel modules.
Force insertion of a kernel module. Must be invoked as root.
Module loader that is normally invoked automatically in a startup script.
Creates module dependency file, usually invoked from startup script.
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 another dangerous command, if misused.
Using our knowledge of administrative commands, let us examine a system script. One of the shortest and simplest to understand scripts is killall, used to suspend running processes at system shutdown.
Example 3-71. killall, from /etc/rc.d/init.d
1 #!/bin/sh 2 3 # --> Comments added by the author of this HOWTO marked by "-->". 4 5 # --> This is part of the 'rc' script package 6 # --> by Miquel van Smoorenburg, <miquels@drinkel.nl.mugnet.org> 7 8 # --> This particular script seems to be Red Hat specific 9 # --> (may not be present in other distributions). 10 11 # Bring down all unneeded services that are still running (there shouldn't 12 # be any, so this is just a sanity check) 13 14 for i in /var/lock/subsys/*; do 15 # --> Standard for/in loop, but since "do" is on same line, 16 # --> it is necessary to add ";". 17 # Check if the script is there. 18 [ ! -f $i ] && continue 19 # --> This is a clever use of an "and list", equivalent to: 20 # --> if [ ! -f $i ]; then continue 21 22 # Get the subsystem name. 23 subsys=${i#/var/lock/subsys/} 24 # --> Match variable name, which, in this case, is the file name. 25 # --> This is the exact equivalent of subsys=`basename $i`. 26 27 # --> It gets it from the lock file name, and since if there 28 # --> is a lock file, that's proof the process has been running. 29 # --> See the "lockfile" entry, above. 30 31 32 # Bring the subsystem down. 33 if [ -f /etc/rc.d/init.d/$subsys.init ]; then 34 /etc/rc.d/init.d/$subsys.init stop 35 else 36 /etc/rc.d/init.d/$subsys stop 37 # --> Suspend running jobs and daemons 38 # --> using the 'stop' shell builtin. 39 fi 40 done |
That wasn't so bad. Aside from a little fancy footwork with variable matching, there is no new material there.
Exercise. In /etc/rc.d/init.d, analyze the halt script. It is a bit longer than killall, but similar in concept. Make a copy of this script somewhere in your home directory and experiment with it (do not run it as root). Do a simulated run with the -vn flags (sh -vn scriptname). Add extensive comments. Change the "action" commands to "echos".
Now, look at some of the more complex scripts in /etc/rc.d/init.d. See if you can understand parts of them. Follow the above procedure to analyze them. For some additional insight, you might also examine the file sysvinitfiles in /usr/doc/initscripts-X.XX, which is part of the "initscripts" documentation.
[1] | NAND is the logical "not-and" operator. Its effect is somewhat similar to subtraction. |