12.9. Miscellaneous Commands

Command Listing

jot, seq

These utilities emit a sequence of integers, with a user selected increment. This can be used to advantage in a for loop.


Example 12-29. Using seq to generate loop arguments

   1 #!/bin/bash
   2 
   3 for a in `seq 80`  # or   for a in $( seq 80 )
   4 # Same as   for a in 1 2 3 4 5 ... 80   (saves much typing!).
   5 # May also use 'jot' (if present on system).
   6 do
   7   echo -n "$a "
   8 done
   9 # Example of using the output of a command to generate 
  10 # the [list] in a "for" loop.
  11 
  12 echo; echo
  13 
  14 
  15 COUNT=80  # Yes, 'seq' may also take a replaceable parameter.
  16 
  17 for a in `seq $COUNT`  # or   for a in $( seq $COUNT )
  18 do
  19   echo -n "$a "
  20 done
  21 
  22 echo
  23 
  24 exit 0

run-parts

The run-parts command [1] executes all the scripts in a target directory, sequentially in ASCII-sorted filename order. Of course, the scripts need to have execute permission.

The crond daemon invokes run-parts to run the scripts in the /etc/cron.* directories.

yes

In its default behavior the yes command feeds a continuous string of the character y followed by a line feed to stdout. A control-c terminates the run. A different output string may be specified, as in yes different string, which would continually output different string to stdout. One might well ask the purpose of this. From the command line or in a script, the output of yes can be redirected or piped into a program expecting user input. In effect, this becomes a sort of poor man's version of expect.

yes | fsck /dev/hda1 runs fsck non-interactively (careful!).

yes | rm -r dirname has same effect as rm -rf dirname (careful!).

Warning

Be very cautious when piping yes to a potentially dangerous system command, such as fsck or fdisk.

banner

Prints arguments as a large vertical banner to stdout, using an ASCII character (default '#'). This may be redirected to a printer for hardcopy.

printenv

Show all the environmental variables set for a particular user.

 bash$ printenv | grep HOME
 HOME=/home/bozo
 	      

lp

The lp and lpr commands send file(s) to the print queue, to be printed as hard copy. [2] These commands trace the origin of their names to the line printers of another era.

bash$ lp file1.txt or bash lp <file1.txt

It is often useful to pipe the formatted output from pr to lp.

bash$ pr -options file1.txt | lp

Formatting packages, such as groff and Ghostscript may send their output directly to lp.

bash$ groff -Tascii file.tr | lp

bash$ gs -options | lp file.ps

Related commands are lpq, for viewing the print queue, and lprm, for removing jobs from the print queue.

tee

[UNIX borrows an idea here from the plumbing trade.]

This is a redirection operator, but with a difference. Like the plumber's tee, it permits "siponing off" the output of a command or commands within a pipe, but without affecting the result. This is useful for printing an ongoing process to a file or paper, perhaps to keep track of it for debugging purposes.

                    tee
                  |------> to file
                  |
   ===============|===============
   command--->----|-operator-->---> result of command(s)
   ===============================
 	      

   1 cat listfile* | sort | tee check.file | uniq > result.file
(The file check.file contains the concatenated sorted "listfiles", before the duplicate lines are removed by uniq.)

mkfifo

This obscure command creates a named pipe, a temporary first-in-first-out buffer for transferring data between processes. [3] Typically, one process writes to the FIFO, and the other reads from it. See Example A-10.

pathchk

This command checks the validity of a filename. If the filename exceeds the maximum allowable length (255 characters) or one or more of the directories in its path is not searchable, then an error message results. Unfortunately, pathchk does not return a recognizable error code, and it is therefore pretty much useless in a script.

dd

This is the somewhat obscure and much feared "data duplicator" command. Originally a utility for exchanging data on magnetic tapes between UNIX minicomputers and IBM mainframes, this command still has its uses. The dd command simply copies a file (or stdin/stdout), but with conversions. Possible conversions are ASCII/EBCDIC, [4] upper/lower case, swapping of byte pairs between input and output, and skipping and/or truncating the head or tail of the input file. A dd --help lists the conversion and other options that this powerful utility takes.

   1 # Exercising 'dd'.
   2 
   3 n=3
   4 p=5
   5 input_file=project.txt
   6 output_file=log.txt
   7 
   8 dd if=$input_file of=$output_file bs=1 skip=$((n-1)) count=$((p-n+1)) 2> /dev/null
   9 # Extracts characters n to p from file $input_file.
  10 
  11 
  12 
  13 
  14 echo -n "hello world" | dd cbs=1 conv=unblock 2> /dev/null
  15 # Echoes "hello world" vertically.
  16 
  17 
  18 # Thanks, S.C.

To demonstrate just how versatile dd is, let's use it to capture keystrokes.


Example 12-30. Capturing Keystrokes

   1 #!/bin/bash
   2 # Capture keystrokes without needing to press ENTER.
   3 
   4 
   5 keypresses=4                      # Number of keypresses to capture.
   6 
   7 
   8 old_tty_setting=$(stty -g)        # Save old terminal settings.
   9 
  10 echo "Press $keypresses keys."
  11 stty -icanon -echo                # Disable canonical mode.
  12                                   # Disable local echo.
  13 keys=$(dd bs=1 count=$keypresses 2> /dev/null)
  14 # 'dd' uses stdin, if "if" not specified.
  15 
  16 stty "$old_tty_setting"           # Restore old terminal settings.
  17 
  18 echo "You pressed the \"$keys\" keys."
  19 
  20 # Thanks, S.C. for showing the way.
  21 exit 0

The dd command can do random access on a data stream.
   1 echo -n . | dd bs=1 seek=4 of=file conv=notrunc
   2 # The "conv=notrunc" option means that the output file will not be truncated.		
   3 
   4 # Thanks, S.C.

The dd command can copy raw data and disk images to and from devices, such as floppies and tape drives (Example A-5). A common use is creating boot floppies.
   1 dd if=kernel-image of=/dev/fd0H1440
Other applications of dd include initializing temporary swap files (Example 29-2) and ramdisks (Example 29-3). It can even do a low-level copy of an entire hard drive partition, although this is not necessarily recommended.

People (with presumably nothing better to do with their time) are constantly thinking of interesting applications of dd.


Example 12-31. Securely deleting a file

   1 #!/bin/bash
   2 # blotout.sh: Erase all traces of a file.
   3 
   4 #  This script overwrites a target file alternately
   5 #+ with random bytes, then zeros before finally deleting it.
   6 #  After that, even examining the raw disk sectors
   7 #+ will not reveal the original file data.
   8 
   9 PASSES=7         # Number of file-shredding passes.
  10 BLOCKSIZE=1      #  I/O with /dev/urandom requires unit block size,
  11                  #+ otherwise you get weird results.
  12 E_BADARGS=70
  13 E_NOT_FOUND=71
  14 E_CHANGED_MIND=72
  15 
  16 if [ -z "$1" ]   # No filename specified.
  17 then
  18   echo "Usage: `basename $0` filename"
  19   exit $E_BADARGS
  20 fi
  21 
  22 file=$1
  23 
  24 if [ ! -e "$file" ]
  25 then
  26   echo "File \"$file\" not found."
  27   exit $E_NOT_FOUND
  28 fi  
  29 
  30 echo; echo -n "Are you absolutely sure you want to blot out \"$file\" (y/n)? "
  31 read answer
  32 case "$answer" in
  33 [nN]) echo "Changed your mind, huh?"
  34       exit $E_CHANGED_MIND
  35       ;;
  36 *)    echo "Blotting out file \"$file\".";;
  37 esac
  38 
  39 
  40 flength=$(ls -l "$file" | awk '{print $5}')  # Field 5 is file length.
  41 
  42 pass_count=1
  43 
  44 echo
  45 
  46 while [ "$pass_count" -le "$PASSES" ]
  47 do
  48   echo "Pass #$pass_count"
  49   sync         # Flush buffers.
  50   dd if=/dev/urandom of=$file bs=$BLOCKSIZE count=$flength
  51                # Fill with random bytes.
  52   sync         # Flush buffers again.
  53   dd if=/dev/zero of=$file bs=$BLOCKSIZE count=$flength
  54                # Fill with zeros.
  55   sync         # Flush buffers yet again.
  56   let "pass_count += 1"
  57   echo
  58 done  
  59 
  60 
  61 rm -f $file    # Finally, delete scrambled and shredded file.
  62 sync           # Flush buffers a final time.
  63 
  64 echo "File \"$file\" blotted out and deleted."; echo
  65 
  66 
  67 #  This is a fairly secure, if inefficient and slow method
  68 #+ of thoroughly "shredding" a file. The "shred" command,
  69 #+ part of the GNU "fileutils" package, does the same thing,
  70 #+ but more efficiently.
  71 
  72 #  The file cannot not be "undeleted" or retrieved by normal methods.
  73 #  However...
  74 #+ this simple method will likely *not* withstand forensic analysis.
  75 
  76 
  77 #  Tom Vier's "wipe" file-deletion package does a much more thorough job
  78 #+ of file shredding than this simple script.
  79 #     http://www.ibiblio.org/pub/Linux/utils/file/wipe-2.0.0.tar.bz2
  80 
  81 #  For an in-depth analysis on the topic of file deletion and security,
  82 #+ see Peter Gutmann's paper,
  83 #+     "Secure Deletion of Data From Magnetic and Solid-State Memory".
  84 #           http://www.cs.auckland.ac.nz/~pgut001/secure_del.html
  85 
  86 
  87 exit 0

od

The od, or octal dump filter converts input (or files) to octal (base-8) or other bases. This is useful for viewing or processing binary data files or otherwise unreadable system device files, such as /dev/urandom, and as a filter for binary data. See Example 9-20 and Example 12-9.

hexdump

Performs a hexadecimal, octal, decimal, or ASCII dump of a binary file. This command is the rough equivalent of od, above, but not nearly as useful.

m4

A hidden treasure, m4 is a powerful macro processor [5] utility, virtually a complete language. In fact, m4 combines some of the functionality of eval, tr, and awk.


Example 12-32. Using m4

   1 #!/bin/bash
   2 # m4.sh: Using the m4 macro processor
   3 
   4 # Strings
   5 string=abcdA01
   6 echo "len($string)" | m4                       # 7
   7 echo "substr($string,4)" | m4                  # A01
   8 echo "regexp($string,[0-1][0-1],\&Z)" | m4     # 01Z
   9 
  10 # Arithmetic
  11 echo "incr(22)" | m4                           # 23
  12 echo "eval(99 / 3)" | m4                       # 33
  13 
  14 exit 0

Notes

[1]

This is actually a script adapted from the Debian Linux distribution.

[2]

The print queue is the group of jobs "waiting in line" to be printed.

[3]

For an excellent overview of this topic, see Andy Vaught's article, Introduction to Named Pipes, in the September, 1997 issue of Linux Journal.

[4]

EBCDIC (pronounced "ebb-sid-ic") is an acronym for Extended Binary Coded Decimal Interchange Code. This is an IBM data format no longer in much use. A bizarre application of the conv=ebcdic option of dd is as a quick 'n easy, but not very secure text file encoder.
   1 cat $file | dd conv=swab,ebcdic > $file_encrypted
   2 # Encode (looks like gibberish).		    
   3 # Might as well switch bytes (swab), too, for a little extra obscurity.
   4 
   5 cat $file_encrypted | dd conv=swab,ascii > $file_plaintext
   6 # Decode.

[5]

A macro is a symbolic constant that expands into a command string or a set of operations on parameters.