home *** CD-ROM | disk | FTP | other *** search
/ The Hacker's Encyclopedia 1998 / hackers_encyclopedia.iso / hacking / unix / unixq_2.txt < prev    next >
Encoding:
Internet Message Format  |  2003-06-11  |  62.0 KB

  1. Subject: Frequently Asked Questions about Unix - with Answers [Monthly posting]
  2.  
  3. [Last changed: $Date: 91/01/03 14:27:19 $ by $Author: sahayman $]
  4.  
  5. This article contains the answers to some Frequently Asked Questions
  6. often seen in comp.unix.questions.  Please don't ask these questions
  7. again, they've been answered plenty of times already - and please don't
  8. flame someone just because they may not have read this particular
  9. posting.  Thank you.
  10.  
  11.  
  12. This article includes answers to:
  13.  
  14.     1)  How do I remove a file whose name begins with a "-" ?
  15.     2)  How do I remove a file with funny characters in the filename ?
  16.     3)  How do I get a recursive directory listing?
  17.     4)  How do I get the current directory into my prompt?
  18.     5)  How do I read characters from a terminal without requiring the user
  19.           to hit RETURN?
  20.     6)  How do I read characters from the terminal in a shell script?
  21.     7)  How do I check to see if there are characters to be read without
  22.           actually reading?
  23.     8)  How do I find the name of an open file?
  24.     9)  How do I rename "*.foo" to "*.bar", or change file names
  25.           to lowercase?
  26.     10) Why do I get [some strange error message] when I
  27.           "rsh host command" ?
  28.     11) How do I find out the creation time of a file?
  29.     12) How do I use "rsh" without having the rsh hang around
  30.           until the remote command has completed?
  31.     13) How do I truncate a file?
  32.     14) How do I {set an environment variable, change directory} inside a
  33.           program or shell script and have that change affect my
  34.           current shell?
  35.     15) Why doesn't find's "{}" symbol do what I want?
  36.     16) How do I redirect stdout and stderr separately in csh?
  37.     17) How do I set the permissions on a symbolic link?
  38.     18) When someone refers to 'rn(1)' or 'ctime(3)', what does
  39.           the number in parentheses mean?
  40.     19) What does {awk,grep,fgrep,egrep,biff,cat,gecos,nroff,troff,tee,bss}
  41.           stand for?
  42.     20) How does the gateway between "comp.unix.questions" and the
  43.         "info-unix" mailing list work?
  44.     21) How do I "undelete" a file?
  45.     22) How can a process detect if it's running in the background?
  46.     23) How can an executing program determine its own pathname?
  47.     24) How do I tell inside .cshrc if I'm a login shell?
  48.     25) Why doesn't redirecting a loop work as intended?  (Bourne shell)
  49.     26) How do I use popen() to open a process for reading AND writing?
  50.     27) How do I run 'passwd', 'ftp', 'telnet', 'tip' and other interactive
  51.           programs from a shell script or in the background?
  52.     28) How do I sleep() in a C program for less than one second?
  53.     29) How can I get setuid shell scripts to work?
  54.     30) What are some useful Unix or C books?
  55.     31) How do I construct a shell glob-pattern that matches all files
  56.         except "." and ".." ?
  57.     32) How do I pronounce "vi" , or "!", or "/*", or ...?
  58.  
  59.  
  60.     If you're looking for the answer to, say, question 14, and want to skip
  61.     everything else, you can search ahead for the regular expression "^14)".  
  62.  
  63. While these are all legitimate questions, they seem to crop up in
  64. comp.unix.questions on an annual basis, usually followed by plenty
  65. of replies (only some of which are correct) and then a period of
  66. griping about how the same questions keep coming up.  You may also like
  67. to read the monthly article "Answers to Frequently Asked Questions"
  68. in the newsgroup "news.announce.newusers", which will tell you what
  69. "UNIX" stands for.
  70.  
  71. With the variety of Unix systems in the world, it's hard to guarantee
  72. that these answers will work everywhere.  Read your local manual pages
  73. before trying anything suggested here.  If you have suggestions or
  74. corrections for any of these answers, please send them to to
  75. sahayman@iuvax.cs.indiana.edu or iuvax!sahayman.
  76.  
  77. 1)  How do I remove a file whose name begins with a "-" ?
  78.  
  79.     Figure out some way to name the file so that it doesn't
  80.     begin with a dash.  The simplest answer is to use   
  81.  
  82.         rm ./-filename
  83.  
  84.     (assuming "-filename" is in the current directory, of course.)
  85.     This method of avoiding the interpretation of the "-" works
  86.     with other commands too.
  87.  
  88.     Many commands, particularly those that have been written to use
  89.     the "getopt(3)" argument parsing routine, accept a "--" argument
  90.     which means "this is the last option, anything after this is not
  91.     an option", so your version of rm might handle "rm -- -filename".
  92.     Some versions of rm that don't use getopt() treat a single "-"
  93.     in the same way, so you can also try "rm - -filename".
  94.     
  95. 2)  How do I remove a file with funny characters in the filename ?
  96.  
  97.     The  classic answers are
  98.  
  99.     rm -i some*pattern*that*matches*only*the*file*you*want
  100.  
  101.     which asks you whether you want to remove each file matching
  102.     the indicated pattern;  depending on your shell, this may
  103.     not work if the filename has a character with the 8th bit set
  104.     (the shell may strip that off);
  105.     
  106.     and
  107.  
  108.     rm -ri .
  109.  
  110.     which asks you whether to remove each file in the directory.
  111.     Answer "y" to the problem file and "n" to everything else.
  112.     Unfortunately this doesn't work with many versions of rm.
  113.     Also unfortunately, this will walk through every subdirectory
  114.     of ".", so you might want to "chmod a-x" those directories
  115.     temporarily to make them unsearchable.
  116.  
  117.     Always take a deep breath and think about what you're doing
  118.     and double check what you typed when you use rm's "-r" flag
  119.     or a wildcard on the command line;
  120.  
  121.     and
  122.  
  123.     find . -type f ... -ok rm '{}' \;
  124.  
  125.     where "..." is a group of predicates that uniquely identify the
  126.     file.  One possibility is to figure out the inode number
  127.     of the problem file (use "ls -i .") and then use
  128.  
  129.     find . -inum 12345 -ok rm '{}' \;
  130.     
  131.     or
  132.     find . -inum 12345 -ok mv '{}' new-file-name \;
  133.     
  134.     
  135.     "-ok" is a safety check - it will prompt you for confirmation of the
  136.     command it's about to execute.  You can use "-exec" instead to avoid
  137.     the prompting, if you want to live dangerously, or if you suspect
  138.     that the filename may contain a funny character sequence that will mess
  139.     up your screen when printed.
  140.  
  141.     If none of these work, find your system manager.
  142.  
  143. 3)  How do I get a recursive directory listing?
  144.  
  145.     One of the following may do what you want:
  146.  
  147.     ls -R             (not all versions of "ls" have -R)
  148.     find . -print        (should work everywhere)
  149.     du -a .            (shows you both the name and size)
  150.     
  151.     If you're looking for a wildcard pattern that will match
  152.     all ".c" files in this directory and below, you won't find one,
  153.     but you can use
  154.  
  155.     % some-command `find . -name '*.c' -print`
  156.  
  157.     "find" is a powerful program.  Learn about it.
  158.  
  159. 4)  How do I get the current directory into my prompt?
  160.  
  161.     It depends which shell you are using.  It's easy with some shells,
  162.     hard or impossible with others.
  163.     
  164.     C Shell (csh):
  165.     Put this in your .cshrc - customize the prompt variable
  166.     the way you want.
  167.  
  168.         alias setprompt 'set prompt="${cwd}% "'
  169.         setprompt        # to set the initial prompt
  170.         alias cd 'chdir \!* && setprompt'
  171.     
  172.     If you use pushd and popd, you'll also need
  173.  
  174.         alias pushd 'pushd \!* && setprompt'
  175.         alias popd  'popd  \!* && setprompt'
  176.  
  177.     Some C shells don't keep a $cwd variable - you can use
  178.     `pwd` instead.
  179.  
  180.     If you just want the last component of the current directory
  181.     in your prompt ("mail% " instead of "/usr/spool/mail% ")
  182.     you can use
  183.  
  184.         alias setprompt 'set prompt="$cwd:t% "'
  185.  
  186.     
  187.     Some older csh's get the meaning of && and || reversed.
  188.     Try doing:
  189.  
  190.         false && echo bug
  191.  
  192.     If it prints "bug", you need to switch && and || (and get
  193.     a better version of csh.)
  194.  
  195.  
  196.     Bourne Shell (sh):
  197.  
  198.     If you have a newer version of the Bourne Shell (SVR2 or newer)
  199.     you can use a shell function to make your own command, "xcd" say:
  200.  
  201.         xcd() { cd $* ; PS1="`pwd` $ "; }
  202.  
  203.     If you have an older Bourne shell, it's complicated but not impossible.
  204.     Here's one way.  Add this to your .profile file:
  205.  
  206.         LOGIN_SHELL=$$ export LOGIN_SHELL
  207.         CMDFILE=/tmp/cd.$$ export CMDFILE
  208.         # 16 is SIGURG, pick some signal that isn't likely to be used
  209.         PROMPTSIG=16 export PROMPTSIG
  210.         trap '. $CMDFILE' $PROMPTSIG
  211.  
  212.     and then put this executable script (without the indentation!),
  213.     let's call it "xcd", somewhere in your PATH 
  214.  
  215.         : xcd directory - change directory and set prompt
  216.         : by signalling the login shell to read a command file
  217.         cat >${CMDFILE?"not set"} <<EOF
  218.         cd $1
  219.         PS1="\`pwd\`$ "
  220.         EOF
  221.         kill -${PROMPTSIG?"not set"} ${LOGIN_SHELL?"not set"}
  222.  
  223.     Now change directories with "xcd /some/dir".
  224.  
  225.  
  226.     Korn Shell (ksh):
  227.  
  228.     Put this in your .profile file:
  229.         PS1='$PWD $ '
  230.     
  231.     If you just want the last component of the directory, use
  232.         PS1='${PWD##*/} $ '
  233.  
  234.     T C shell (tcsh)
  235.  
  236.     Tcsh is a popular enhanced version of csh with some extra
  237.     builtin variables (and many other features):
  238.  
  239.         %~        the current directory, using ~ for $HOME
  240.         %d or %/    the full pathname of the current directory
  241.         %c or %.    the trailing component of the current directory
  242.  
  243.     so you can do
  244.  
  245.         set prompt='%~ '
  246.  
  247.     BASH (FSF's "Bourne Again SHell")
  248.     
  249.     \w in $PS1 gives the full pathname of the current directory,
  250.     with ~ expansion for $HOME;  \W gives the basename of
  251.     the current directory.  So, in addition to the above sh and
  252.     ksh solutions, you could use
  253.  
  254.         PS1='\w $ '    
  255.     or
  256.         PS1='\W $ '
  257.         
  258. 5)  How do I read characters from a terminal without requiring the user
  259.     to hit RETURN?
  260.  
  261.     Check out cbreak mode in BSD, ~ICANON mode in SysV. 
  262.  
  263.     If you don't want to tackle setting the terminal parameters
  264.     yourself (using the "ioctl(2)" system call) you can let the stty
  265.     program do the work - but this is slow and inefficient, and you
  266.     should change the code to do it right some time:
  267.  
  268.     #include <stdio.h>
  269.     main()
  270.     {
  271.         int c;
  272.  
  273.         printf("Hit any character to continue\n");
  274.         /*
  275.          * ioctl() would be better here; only lazy
  276.          * programmers do it this way:
  277.          */
  278.         system("/bin/stty cbreak");        /* or "stty raw" */
  279.         c = getchar();
  280.         system("/bin/stty -cbreak");
  281.         printf("Thank you for typing %c.\n", c);
  282.  
  283.         exit(0);
  284.     }
  285.  
  286.     You might like to check out the documentation for the "curses"
  287.     library of portable screen functions.  Often if you're interested
  288.     in single-character I/O like this, you're also interested in doing
  289.     some sort of screen display control, and the curses library
  290.     provides various portable routines for both functions.
  291.  
  292.  
  293.  
  294. 6)  How do I read characters from the terminal in a shell script?
  295.  
  296.     In sh, use read.  It is most common to use a loop like
  297.  
  298.         while read line
  299.         do
  300.             ...
  301.         done
  302.  
  303.     In csh, use $< like this:
  304.     
  305.         while ( 1 )
  306.         set line = "$<"
  307.         if ( "$line" == "" ) break
  308.         ...
  309.         end
  310.  
  311.     Unfortunately csh has no way of distinguishing between
  312.     a blank line and an end-of-file.
  313.  
  314.     If you're using sh and want to read a *single* character from
  315.     the terminal, you can try something like
  316.  
  317.         echo -n "Enter a character: "
  318.         stty cbreak        # or  stty raw
  319.         readchar=`dd if=/dev/tty bs=1 count=1 2>/dev/null`
  320.         stty -cbreak
  321.  
  322.         echo "Thank you for typing a $readchar ."
  323.  
  324. 7)  How do I check to see if there are characters to be read without
  325.     actually reading?
  326.  
  327.     Certain versions of UNIX provide ways to check whether
  328.     characters are currently available to be read from a file
  329.     descriptor.  In BSD, you can use select(2).  You can also use
  330.     the FIONREAD ioctl (see tty(4)), which returns the number of
  331.     characters waiting to be read, but only works on terminals,
  332.     pipes and sockets.  In System V Release 3, you can use poll(2),
  333.     but that only works on streams.  In Xenix - and therefore
  334.     Unix SysV r3.2 and later - the rdchk() system call reports
  335.     whether a read() call on a given file descriptor will block.
  336.  
  337.     There is no way to check whether characters are available to be
  338.     read from a FILE pointer.  (You could poke around inside stdio data
  339.     structures to see if the input buffer is nonempty, but that wouldn't
  340.     work since you'd have no way of knowing what will happen the next
  341.     time you try to fill the buffer.)
  342.  
  343.     Sometimes people ask this question with the intention of writing
  344.         if (characters available from fd)
  345.             read(fd, buf, sizeof buf);
  346.     in order to get the effect of a nonblocking read.  This is not the
  347.     best way to do this, because it is possible that characters will
  348.     be available when you test for availability, but will no longer
  349.     be available when you call read.  Instead, set the O_NDELAY flag
  350.     (which is also called FNDELAY under BSD) using the F_SETFL option
  351.     of fcntl(2).  Older systems (Version 7, 4.1 BSD) don't have O_NDELAY;
  352.     on these systems the closest you can get to a nonblocking read is
  353.     to use alarm(2) to time out the read.
  354.  
  355.  
  356. 8)  How do I find the name of an open file?
  357.  
  358.     In general, this is too difficult.  The file descriptor may
  359.     be attached to a pipe or pty, in which case it has no name.
  360.     It may be attached to a file that has been removed.  It may
  361.     have multiple names, due to either hard or symbolic links.
  362.  
  363.     If you really need to do this, and be sure you think long
  364.     and hard about it and have decided that you have no choice,
  365.     you can use find with the -inum and possibly -xdev option,
  366.     or you can use ncheck, or you can recreate the functionality
  367.     of one of these within your program.  Just realize that
  368.     searching a 600 megabyte filesystem for a file that may not
  369.     even exist is going to take some time.
  370.  
  371.  
  372. 9) How do I rename "*.foo" to "*.bar", or change file names to lowercase?
  373.     
  374.     Why doesn't "mv *.foo *.bar" work?  Think about how the shell
  375.     expands wildcards.   "*.foo" and "*.bar" are expanded before the mv
  376.     command ever sees the arguments.  Depending on your shell, this
  377.     can fail in a couple of ways.  CSH prints "No match." because
  378.     it can't match "*.bar".  SH executes "mv a.foo b.foo c.foo *.bar",
  379.     which will only succeed if you happen to have a single
  380.     directory named "*.bar", which is very unlikely and almost
  381.     certainly not what you had in mind.
  382.  
  383.     Depending on your shell, you can do it with a loop to "mv" each
  384.     file individually.  If your system has "basename", you can use:
  385.  
  386.     C Shell:
  387.     foreach f ( *.foo )
  388.         set base=`basename $f .foo`
  389.         mv $f $base.bar
  390.     end
  391.  
  392.     Bourne Shell:
  393.     for f in *.foo; do
  394.         base=`basename $f .foo`
  395.         mv $f $base.bar
  396.     done
  397.  
  398.     Some shells have their own variable substitution features, so instead
  399.     of using "basename", you can use simpler loops like:
  400.  
  401.     C Shell:
  402.  
  403.     foreach f ( *.foo )
  404.         mv $f $f:r.bar
  405.     end
  406.  
  407.     Korn Shell:
  408.  
  409.     for f in *.foo; do
  410.         mv $f ${f%foo}bar
  411.     done
  412.     
  413.     If you don't have "basename" or want to do something like
  414.     renaming foo.* to bar.*, you can use something like "sed" to
  415.     strip apart the original file name in other ways, but
  416.     the general looping idea is the same.  You can also convert
  417.     file names into "mv" commands with 'sed', and hand the commands
  418.     off to "sh" for execution.  Try
  419.  
  420.     ls -d *.foo | sed -e 's/.*/mv & &/' -e 's/foo$/bar/' | sh
  421.  
  422.     A program by Vladimir Lanin called "mmv" that does this job nicely
  423.     was posted to comp.sources.unix (Volume 21, issues 87 and 88) in
  424.     April 1990.  It lets you use
  425.  
  426.     mmv '*.foo' '=1.bar'
  427.  
  428.     Shell loops like the above can also be used to translate
  429.     file names from upper to lower case or vice versa.  You could use
  430.     something like this to rename uppercase files to lowercase:
  431.  
  432.     C Shell:
  433.         foreach f ( * )
  434.         mv $f `echo $f | tr '[A-Z]' '[a-z]'`
  435.         end
  436.     Bourne Shell:
  437.         for f in *; do
  438.         mv $f `echo $f | tr '[A-Z]' '[a-z]'`
  439.         done
  440.     Korn Shell:
  441.         typeset -l l
  442.         for f in *; do
  443.         l="$f"
  444.         mv $f $l
  445.         done
  446.  
  447.  
  448.     If you wanted to be really thorough and handle files with
  449.     `funny' names (embedded blanks or whatever) you'd need to use
  450.     
  451.     Bourne Shell:
  452.  
  453.         for f in *; do
  454.         eval mv '"$f"' \"`echo "$f" | tr '[A-Z]' '[a-z]'`\"
  455.         done
  456.     
  457.     (Some versions of "tr" require the [ and ], some don't.  It happens 
  458.      to be harmless to include them in this particular example; versions of
  459.      tr that don't want the [] will conveniently think they are supposed
  460.      to translate '[' to '[' and ']' to ']').
  461.  
  462.     If you have the "perl" language installed, you may find this rename
  463.     script by Larry Wall very useful.  It can be used to accomplish a
  464.     wide variety of filename changes.
  465.  
  466.     #!/usr/bin/perl
  467.     #
  468.     # rename script examples from lwall:
  469.     #       rename 's/\.orig$//' *.orig
  470.     #       rename 'y/A-Z/a-z/ unless /^Make/' *
  471.     #       rename '$_ .= ".bad"' *.f
  472.     #       rename 'print "$_: "; s/foo/bar/ if <stdin> =~ /^y/i' *
  473.  
  474.     $op = shift;
  475.     for (@ARGV) {
  476.         $was = $_;
  477.         eval $op;
  478.         die $@ if $@;
  479.         rename($was,$_) unless $was eq $_;
  480.     }
  481.  
  482.  
  483. 10) Why do I get [some strange error message] when I "rsh host command" ?
  484.  
  485.     (We're talking about the remote shell program "rsh" or sometimes "remsh";
  486.      on some machines, there is a restricted shell called "rsh", which
  487.      is a different thing.)
  488.  
  489.     If your remote account uses the C shell, the remote host will
  490.     fire up a C shell to execute 'command' for you, and that shell
  491.     will read your remote .cshrc file.  Perhaps your .cshrc contains
  492.     a "stty", "biff" or some other command that isn't appropriate
  493.     for a non-interactive shell.  The unexpected output or error
  494.     message from these commands can screw up your rsh in odd ways.
  495.  
  496.     Fortunately, the fix is simple.  There are, quite possibly, a whole
  497.     *bunch* of operations in your ".cshrc" (e.g., "set history=N") that are
  498.     simply not worth doing except in interactive shells.  What you do is
  499.     surround them in your ".cshrc" with:
  500.  
  501.         if ( $?prompt ) then
  502.             operations....
  503.         endif
  504.  
  505.     and, since in a non-interactive shell "prompt" won't be set, the
  506.     operations in question will only be done in interactive shells.
  507.  
  508.     You may also wish to move some commands to your .login file; if
  509.     those commands only need to be done when a login session starts up
  510.     (checking for new mail, unread news and so on) it's better
  511.     to have them in the .login file.
  512.  
  513. 11) How do I find out the creation time of a file?
  514.  
  515.     You can't - it isn't stored anywhere.  Files have a last-modified
  516.     time (shown by "ls -l"), a last-accessed time (shown by "ls -lu")
  517.     and an inode change time (shown by "ls -lc"). The latter is often
  518.     referred to as the "creation time" - even in some man pages -  but
  519.     that's wrong; it's also set by such operations as mv, ln,
  520.     chmod, chown and chgrp.
  521.  
  522.     The man page for "stat(2)" discusses this.
  523.  
  524. 12) How do I use "rsh" without having the rsh hang around until the
  525.     remote command has completed?
  526.  
  527.     (See note in question 10 about what "rsh" we're talking about.)
  528.  
  529.     The obvious answers fail:
  530.             rsh machine command &
  531.     or      rsh machine 'command &'
  532.  
  533.     For instance, try doing   rsh machine 'sleep 60 &'
  534.     and you'll see that the 'rsh' won't exit right away.
  535.     It will wait 60 seconds until the remote 'sleep' command
  536.     finishes, even though that command was started in the
  537.     background on the remote machine.  So how do you get
  538.     the 'rsh' to exit immediately after the 'sleep' is started?
  539.  
  540.     The solution - if you use csh on the remote machine:
  541.  
  542.         rsh machine -n 'command >&/dev/null </dev/null &' 
  543.     
  544.     If you use sh on the remote machine:
  545.  
  546.         rsh machine -n 'command >/dev/null 2>&1 </dev/null &' 
  547.  
  548.     Why?  "-n" attaches rsh's stdin to /dev/null so you could run the
  549.     complete rsh command in the background on the LOCAL machine.
  550.     Thus "-n" is equivalent to another specific "< /dev/null".
  551.     Furthermore, the input/output redirections on the REMOTE machine 
  552.     (inside the single quotes) ensure that rsh thinks the session can
  553.     be terminated (there's no data flow any more.)
  554.  
  555.     Note: The file that you redirect to/from on the remote machine
  556.     doesn't have to be /dev/null; any ordinary file will do.
  557.  
  558.     In many cases, various parts of these complicated commands
  559.     aren't necessary.
  560.  
  561. 13) How do I truncate a file?
  562.     
  563.     The BSD function ftruncate() sets the length of a file.  Xenix -
  564.     and therefore SysV r3.2 and later - has the chsize() system call.
  565.     For other systems, the only kind of truncation you can do is
  566.     truncation to length zero with creat() or open(..., O_TRUNC).
  567.  
  568. 14) How do I {set an environment variable, change directory} inside a
  569.       program or shell script and have that change affect my
  570.       current shell?
  571.  
  572.     In general, you can't, at least not without making special
  573.     arrangements.  When a child process is created, it inherits a copy
  574.     of its parent's variables (and current directory).  The child can
  575.     change these values all it wants but the changes won't affect the
  576.     parent shell, since the child is changing a copy of the 
  577.     original data.
  578.  
  579.     Some special arrangements are possible.  Your child process could
  580.     write out the changed variables, if the parent was prepared to read
  581.     the output and interpret it as commands to set its own variables.
  582.  
  583.     Also, shells can arrange to run other shell scripts in the context
  584.     of the current shell, rather than in a child process, so that
  585.     changes will affect the original shell.
  586.  
  587.     For instance, if you have a C shell script named "myscript":
  588.  
  589.     cd /very/long/path
  590.     setenv PATH /something:/something-else
  591.  
  592.     or the equivalent Bourne or Korn shell script
  593.  
  594.     cd /very/long/path
  595.     PATH=/something:/something-else export PATH
  596.  
  597.     and try to run "myscript" from your shell, your shell will fork and run
  598.     the shell script in a subprocess.  The subprocess is also
  599.     running the shell; when it sees the "cd" command it changes
  600.     *its* current directory, and when it sees the "setenv" command
  601.     it changes *its* environment, but neither has any effect on the current
  602.     directory of the shell at which you're typing (your login shell,
  603.     let's say).
  604.  
  605.     In order to get your login shell to execute the script (without forking)
  606.     you have to use the "." command (for the Bourne or Korn shells)
  607.     or the "source" command (for the C shell).  I.e. you type
  608.  
  609.     . myscript
  610.     
  611.     to the Bourne or Korn shells, or
  612.  
  613.     source myscript
  614.  
  615.     to the C shell.
  616.  
  617.     If all you are trying to do is change directory or set an
  618.     environment variable, it will probably be simpler to use a
  619.     C shell alias or Bourne/Korn shell function.  See the "how do
  620.     I get the current directory into my prompt" section
  621.     of this article for some examples.
  622.  
  623. 15) Why doesn't find's "{}" symbol do what I want?
  624.  
  625.     "find" has a -exec option that will execute a particular
  626.     command on all the selected files. Find will replace any "{}"
  627.     it sees with the name of the file currently under consideration.
  628.  
  629.     So, some day you might try to use "find" to run a command on every
  630.     file, one directory at a time.  You might try this:
  631.  
  632.     find /path -type d -exec command {}/\* \;
  633.  
  634.     hoping that find will execute, in turn
  635.  
  636.     command directory1/*
  637.     command directory2/*
  638.     ...
  639.     
  640.     Unfortunately, find only expands the "{}" token when it appears
  641.     by itself.  Find will leave anything else like "{}/*" alone, so
  642.     instead of doing what you want, it will do
  643.  
  644.     command {}/*
  645.     command {}/*
  646.     ...
  647.  
  648.     once for each directory.  This might be a bug, it might be a feature,
  649.     but we're stuck with the current behaviour.
  650.  
  651.     So how do you get around this?  One way would be to write a
  652.     trivial little shell script, let's say "./doit", that
  653.     consists of
  654.     
  655.     command "$1"/*
  656.     
  657.     You could then use
  658.  
  659.     find /path -type d -exec ./doit {} \;
  660.     
  661.     Or if you want to avoid the "./doit" shell script, you can use
  662.  
  663.     find /path -type d -exec sh -c 'command $0/*' {} \;
  664.     
  665.     (This works because within the 'command' of "sh -c 'command' A B C ...",
  666.      $0 expands to A, $1 to B, and so on.)
  667.  
  668.     or you can use the construct-a-command-with-sed trick
  669.  
  670.     find /path -type d -print | sed 's:.*:command &/*:' | sh
  671.  
  672.  
  673.  
  674.     If all you're trying to do is cut down on the number of times
  675.     that "command" is executed, you should see if your system
  676.     has the "xargs" command.  Xargs reads arguments one line at a time
  677.     from the standard input and assembles as many of them as will fit into
  678.     one command line.  You could use
  679.  
  680.     find /path -print | xargs command
  681.     
  682.     which would result in one or more executions of
  683.  
  684.     command file1 file2 file3 file4 dir1/file1 dir1/file2
  685.     
  686.  
  687.     Unfortunately this is not a perfectly robust or secure solution.
  688.     Xargs expects its input lines to be terminated with newlines, so it
  689.     will be confused by files with odd characters such as newlines
  690.     in their names.
  691.  
  692.  
  693. 16) How do I redirect stdout and stderr separately in csh?
  694.  
  695.     In csh, you can redirect stdout with ">", or stdout and stderr
  696.     together with ">&" but there is no direct way to redirect
  697.     stderr only.  The best you can do is
  698.  
  699.         ( command >stdout_file ) >&stderr_file
  700.  
  701.     which runs "command" in a subshell;  stdout is redirected inside
  702.     the subshell to stdout_file, and both stdout and stderr from the
  703.     subshell are redirected to stderr_file, but by this point stdout
  704.     has already been redirected so only stderr actually winds up in
  705.     stderr_file.
  706.  
  707.     Sometimes it's easier to let sh do the work for you.
  708.  
  709.     sh -c 'command >stdout_file 2>stderr_file'
  710.  
  711. 17) How do I set the permissions on a symbolic link?
  712.  
  713.     Permissions on a symbolic link don't really mean anything.  The
  714.     only permissions that count are the permissions on the file that
  715.     the link points to.
  716.  
  717. 18) When someone refers to 'rn(1)' or 'ctime(3)', what does
  718.     the number in parentheses mean?
  719.  
  720.     It looks like some sort of function call, but it isn't.
  721.     These numbers refer to the section of the "Unix manual" where
  722.     the appropriate documentation can be found.  You could type
  723.     "man 3 ctime" to look up the manual page for "ctime" in section 3
  724.     of the manual.
  725.  
  726.     The traditional manual sections are:
  727.  
  728.     1    User-level  commands
  729.     2    System calls
  730.     3    Library functions
  731.     4    Devices and device drivers
  732.     5    File formats
  733.     6    Games
  734.     7    Various miscellaneous stuff - macro packages etc.
  735.     8    System maintenance and operation commands
  736.     
  737.     
  738.     Some Unix versions use non-numeric section names.  For instance,
  739.     Xenix uses "C" for commands and "S" for functions.
  740.  
  741.     Each section has an introduction, which you can read with "man # intro"
  742.     where # is the section number.
  743.  
  744.     Sometimes the number is necessary to differentiate between a
  745.     command and a library routine or system call of the same name.  For
  746.     instance, your system may have "time(1)", a manual page about the
  747.     'time' command for timing programs, and also "time(3)", a manual
  748.     page about the 'time' subroutine for determining the current time.
  749.     You can use "man 1 time" or "man 3 time" to specify which "time"
  750.     man page you're interested in.
  751.  
  752.     You'll often find other sections for local programs or
  753.     even subsections of the sections above - Ultrix has
  754.     sections 3m, 3n, 3x and 3yp among others.
  755.  
  756.  
  757. 19) What does {awk,grep,fgrep,egrep,biff,cat,gecos,nroff,troff,tee,bss}
  758.     stand for?
  759.  
  760.     awk = "Aho Weinberger and Kernighan"
  761.  
  762.     This language was named by its authors, Al Aho, Peter Weinberger and
  763.     Brian Kernighan.
  764.  
  765.     grep = "Global Regular Expression Print"
  766.  
  767.     grep comes from the ed command to print all lines matching a
  768.     certain pattern
  769.  
  770.             g/re/p
  771.  
  772.     where "re" is a "regular expression".
  773.     
  774.     fgrep = "Fixed GREP".
  775.  
  776.     fgrep searches for fixed strings only.  The "f" does not
  777.     stand for "fast" - in fact, "fgrep foobar *.c" is usually slower
  778.     than "egrep foobar *.c"  (Yes, this is kind of surprising. Try it.)
  779.  
  780.     Fgrep still has its uses though, and may be useful when searching
  781.     a file for a larger number of strings than egrep can handle.
  782.  
  783.     egrep = "Extended GREP"
  784.  
  785.     egrep uses fancier regular expressions than grep.
  786.     Many people use egrep all the time, since it has some more
  787.     sophisticated internal algorithms than grep or fgrep,
  788.     and is usually the fastest of the three programs.
  789.  
  790.     cat = "CATenate"
  791.  
  792.     catenate is an obscure word meaning "to connect in a series",
  793.     which is what the "cat" command does to one or more files.
  794.     Not to be confused with C/A/T, the Computer Aided Typesetter.
  795.  
  796.     gecos = "General Electric Comprehensive Operating System"
  797.     
  798.     When GE's large systems division was sold to Honeywell,
  799.     Honeywell dropped the "E" from "GECOS".
  800.  
  801.     Unix's password file has a "pw_gecos" field.  The name is
  802.     a real holdover from the early days.  Dennis Ritchie
  803.     has reported:
  804.  
  805.         "Sometimes we sent printer output or batch jobs
  806.          to the GCOS machine.  The gcos field in the
  807.          password file was a place to stash the information
  808.          for the $IDENT card.  Not elegant."
  809.  
  810.     nroff = "New ROFF"
  811.     troff = "Typesetter new ROFF"
  812.     
  813.     These are descendants of "roff", which was a re-implementation
  814.     of the Multics "runoff" program (a program that you'd use to
  815.     "run off" a good copy of a document).
  816.     
  817.     tee    = T
  818.  
  819.     From plumbing terminology for a T-shaped pipe splitter.
  820.  
  821.     bss = "Block Started by Symbol"
  822.     
  823.     Dennis Ritchie says:
  824.  
  825.         Actually the acronym (in the sense we took it up; it may
  826.         have other credible etymologies) is "Block Started by Symbol."
  827.         It was a pseudo-op in FAP (Fortran Assembly [-er?] Program), an
  828.         assembler for the IBM 704-709-7090-7094 machines.  It defined
  829.         its label and set aside space for a given number of words.
  830.         There was another pseudo-op, BES, "Block Ended by Symbol"
  831.         that did the same except that the label was defined by
  832.         the last assigned word + 1.  (On these machines Fortran
  833.         arrays were stored backwards in storage and were 1-origin.)
  834.  
  835.         The usage is reasonably appropriate, because just as with
  836.         standard Unix loaders, the space assigned didn't have to
  837.         be punched literally into the object deck but was represented
  838.         by a count somewhere.
  839.  
  840.     biff = "BIFF"
  841.  
  842.         This command, which turns on asynchronous mail notification,
  843.     was actually named after a dog at Berkeley.
  844.  
  845.         I can confirm the origin of biff, if you're interested.  Biff
  846.         was Heidi Stettner's dog, back when Heidi (and I, and Bill Joy)
  847.         were all grad students at U.C. Berkeley and the early versions
  848.         of BSD were being developed.   Biff was popular among the
  849.         residents of Evans Hall, and was known for barking at the
  850.         mailman, hence the name of the command.
  851.  
  852.     Confirmation courtesy of Eric Cooper, Carnegie Mellon
  853.     University
  854.  
  855.     Don Libes' book "Life with Unix" contains lots more of these
  856.     tidbits.
  857.  
  858.  
  859. 20) How does the gateway between "comp.unix.questions" and the
  860.     "info-unix" mailing list work?
  861.  
  862.     "Info-Unix" and "Unix-Wizards" are mailing list versions of
  863.     comp.unix.questions and comp.unix.wizards respectively.
  864.     There should be no difference in content between the
  865.     mailing list and the newsgroup.   
  866.  
  867.     [Note: The newsgroup "comp.unix.wizards" was recently
  868.     deleted, but the "Unix-Wizards" mailing list still exists.
  869.     I'm not really sure how this is all going to sort itself out.]
  870.  
  871.     To get on or off either of these lists, send mail to
  872.     Info-Unix-Request@brl.mil or Unix-Wizards-Request@brl.mil .
  873.     Be sure to use the '-Request'.  Don't expect an immediate response.
  874.  
  875.     Here are the gory details, courtesy of the list's maintainer, Bob Reschly.
  876.  
  877.     ==== postings to info-UNIX and UNIX-wizards lists ====
  878.  
  879.        Anything submitted to the list is posted; I do not moderate incoming
  880.     traffic -- BRL functions as a reflector.  Postings submitted by Internet
  881.     subscribers should be addressed to the list address (info-UNIX or UNIX-
  882.     wizards);  the '-request' addresses are for correspondence with the list
  883.     maintainer [me].  Postings submitted by USENET readers should be
  884.     addressed to the appropriate news group (comp.unix.questions or
  885.     comp.unix.wizards).
  886.  
  887.        For Internet subscribers, received traffic will be of two types;
  888.     individual messages, and digests.  Traffic which comes to BRL from the
  889.     Internet and BITNET (via the BITNET-Internet gateway) is immediately
  890.     resent to all addressees on the mailing list.  Traffic originating on
  891.     USENET is gathered up into digests which are sent to all list members
  892.     daily.
  893.  
  894.        BITNET traffic is much like Internet traffic.  The main difference is
  895.     that I maintain only one address for traffic destined to all BITNET
  896.     subscribers. That address points to a list exploder which then sends
  897.     copies to individual BITNET subscribers.  This way only one copy of a
  898.     given message has to cross the BITNET-Internet gateway in either
  899.     direction.
  900.  
  901.        USENET subscribers see only individual messages.  All messages
  902.     originating on the Internet side are forwarded to our USENET machine.
  903.     They are then posted to the appropriate newsgroup.  Unfortunately,
  904.     for gatewayed messages, the sender becomes "news@brl-adm".  This is
  905.     currently an unavoidable side-effect of the software which performs the
  906.     gateway function.
  907.  
  908.        As for readership, USENET has an extremely large readership - I would
  909.     guess several thousand hosts and tens of thousands of readers.  The
  910.     master list maintained here at BRL runs about two hundred fifty entries
  911.     with roughly ten percent of those being local redistribution lists.
  912.     I don't have a good feel for the size of the BITNET redistribution, but
  913.     I would guess it is roughly the same size and composition as the master
  914.     list.  Traffic runs 150K to 400K bytes per list per week on average.
  915.  
  916. 21) How do I "undelete" a file?
  917.  
  918.     Someday, you are going to accidentally type something like "rm * .foo",
  919.     and find you just deleted "*" instead of "*.foo".  Consider it a rite
  920.     of passage.
  921.  
  922.     Of course, any decent systems administrator should be doing regular
  923.     backups.  Check with your sysadmin to see if a recent backup copy
  924.     of your file is available.  But if it isn't, read on.
  925.  
  926.     For all intents and purposes, when you delete a file with "rm" it is
  927.     gone.  Once you "rm" a file, the system totally forgets which blocks
  928.     scattered around the disk comprised your file.  Even worse, the blocks
  929.     from the file you just deleted are going to be the first ones taken
  930.     and scribbled upon when the system needs more disk space.  However,
  931.     never say never.  It is theoretically possible *if* you shut down
  932.     the system immediately after the "rm" to recover portions of the data.
  933.     However, you had better have a very wizardly type person at hand with
  934.     hours or days to spare to get it all back.
  935.  
  936.     Your first reaction when you "rm" a file by mistake is why not make
  937.     a shell alias or procedure which changes "rm" to move files into a
  938.     trash bin rather than delete them?  That way you can recover them if
  939.     you make a mistake, and periodically clean out your trash bin.  Two
  940.     points:  first, this is generally accepted as a *bad* idea.  You will
  941.     become dependent upon this behaviour of "rm", and you will find
  942.     yourself someday on a normal system where "rm" is really "rm", and
  943.     you will get yourself in trouble.  Second, you will eventually find
  944.     that the hassle of dealing with the disk space and time involved in
  945.     maintaining the trash bin, it might be easier just to be a bit more
  946.     careful with "rm".  For starters, you should look up the "-i" option
  947.     to "rm" in your manual.
  948.  
  949.     If you are still undaunted, then here is a possible simple answer.  You
  950.     can create yourself a "can" command which moves files into a
  951.     trashcan directory. In csh(1) you can place the following commands
  952.     in the ".login" file in your home directory:
  953.  
  954.     alias can    'mv \!* ~/.trashcan'       # junk file(s) to trashcan
  955.     alias mtcan    'rm -f ~/.trashcan/*'       # irretrievably empty trash
  956.     if ( ! -d ~/.trashcan ) mkdir ~/.trashcan  # ensure trashcan exists
  957.  
  958.     You might also want to put a:
  959.  
  960.     rm -f ~/.trashcan/*
  961.  
  962.     in the ".logout" file in your home directory to automatically empty
  963.     the trash when you log out.  (sh and ksh versions are left as an
  964.     exercise for the reader.)
  965.  
  966.     MIT's Project Athena has produced a comprehensive
  967.     delete/undelete/expunge/purge package, which can serve as a
  968.     complete replacement for rm which allows file recovery.  This
  969.     package was posted to comp.sources.unix (volume 18, issue 73).
  970.  
  971.  
  972. 22) How can a process detect if it's running in the background?
  973.  
  974.     First of all: do you want to know if you're running in the background,
  975.     or if you're running interactively? If you're deciding whether or
  976.     not you should print prompts and the like, that's probably a better
  977.     criterion. Check if standard input is a terminal:
  978.  
  979.         sh: if [ -t 0 ]; then ... fi
  980.         C: if(isatty(0)) { ... }
  981.  
  982.     In general, you can't tell if you're running in the background.
  983.     The fundamental problem is that different shells and different
  984.     versions of UNIX have different notions of what "foreground" and
  985.     "background" mean - and on the most common type of system with a
  986.     better-defined notion of what they mean, programs can be moved
  987.     arbitrarily between foreground and background!
  988.  
  989.     UNIX systems without job control typically put a process into the
  990.     background by ignoring SIGINT and SIGQUIT and redirecting the standard
  991.     input to "/dev/null"; this is done by the shell.
  992.  
  993.     Shells that support job control, on UNIX systems that support job
  994.     control, put a process into the background by giving it a process group
  995.     ID different from the process group to which the terminal belongs.  They
  996.     move it back into the foreground by setting the terminal's process group
  997.     ID to that of the process.  Shells that do *not* support job control, on
  998.     UNIX systems that support job control, typically do what shells do on
  999.     systems that don't support job control.
  1000.  
  1001. 23) How can an executing program determine its own pathname?
  1002.  
  1003.     Your program can look at argv[0]; if it begins with a "/",
  1004.     it is probably the absolute pathname to your program, otherwise
  1005.     your program can look at every directory named in the environment
  1006.     variable PATH and try to find the first one that contains an
  1007.     executable file whose name matches your program's argv[0]
  1008.     (which by convention is the name of the file being executed).
  1009.     By concatenating that directory and the value of argv[0] you'd
  1010.     probably have the right name.
  1011.     
  1012.     You can't really be sure though, since it is quite legal for one
  1013.     program to exec() another with any value of argv[0] it desires.
  1014.     It is merely a convention that new programs are exec'd with the
  1015.     executable file name in argv[0].
  1016.  
  1017.     For instance, purely a hypothetical example:
  1018.     
  1019.     #include <stdio.h>
  1020.     main()
  1021.     {
  1022.         execl("/usr/games/rogue", "vi Thesis", (char *)NULL);
  1023.     }
  1024.  
  1025.     The executed program thinks its name (its argv[0] value) is
  1026.     "vi Thesis".   (Certain other programs might also think that
  1027.     the name of the program you're currently running is "vi Thesis",
  1028.     but of course this is just a hypothetical example, don't
  1029.     try it yourself :-)
  1030.     
  1031. 24) How do I tell inside .cshrc if I'm a login shell?
  1032.  
  1033.     When people ask this, they usually mean either
  1034.  
  1035.     How can I tell if it's an interactive shell?
  1036.     or
  1037.     How can I tell if it's a top-level shell?
  1038.     
  1039.     You could perhaps determine if your shell truly is a login shell
  1040.     (i.e. is going to source ".login" after it is done with ".cshrc")
  1041.     by fooling around with "ps" and "$$"; if you're really interested
  1042.     in the other two questions, here's one way you can organize
  1043.     your .cshrc to find out.
  1044.  
  1045.  
  1046.     if (! $?CSHLEVEL) then
  1047.         #
  1048.         # This is a "top-level" shell,
  1049.         # perhaps a login shell, perhaps a shell started up by
  1050.         # 'rsh machine some-command'
  1051.         # This is where we should set PATH and anything else we
  1052.         # want to apply to every one of our shells.
  1053.         #
  1054.         setenv      CSHLEVEL        0
  1055.         set home = ~username        # just to be sure
  1056.         source ~/.env               # environment stuff we always want
  1057.     else
  1058.         # 
  1059.         # This shell is a child of one of our other shells so
  1060.         # we don't need to set all the environment variables again.
  1061.         #
  1062.         set tmp = $CSHLEVEL
  1063.         @ tmp++
  1064.         setenv      CSHLEVEL        $tmp
  1065.     endif
  1066.  
  1067.     # Exit from .cshrc if not interactive, e.g. under rsh 
  1068.     if (! $?prompt) exit
  1069.  
  1070.     # Here we could set the prompt or aliases that would be useful
  1071.     # for interactive shells only.
  1072.  
  1073.     source ~/.aliases
  1074.  
  1075. 25) Why doesn't redirecting a loop work as intended?  (Bourne shell)
  1076.  
  1077.     Take the following example:
  1078.  
  1079.     foo=bar
  1080.  
  1081.     while read line
  1082.     do
  1083.         # do something with $line
  1084.         foo=bletch
  1085.     done < /etc/passwd
  1086.  
  1087.     echo "foo is now: $foo"
  1088.  
  1089.     Despite the assignment ``foo=bletch'' this will print ``foo is now: bar''
  1090.     in many implementations of the Bourne shell.  Why?
  1091.     Because of the following, often undocumented, feature of historic
  1092.     Bourne shells: redirecting a control structure (such as a loop, or an
  1093.     ``if'' statement) causes a subshell to be created, in which the structure
  1094.     is executed; variables set in that subshell (like the ``foo=bletch''
  1095.     assignment) don't affect the current shell, of course.
  1096.  
  1097.     The POSIX 1003.2 Shell and Tools Interface standardization committee
  1098.     forbids the behaviour described above, i.e. in P1003.2 conformant
  1099.     Bourne shells the example will print ``foo is now: bletch''.
  1100.  
  1101.     In historic (and P1003.2 conformant) implementations you can use the
  1102.     following `trick' to get around the redirection problem:
  1103.  
  1104.     foo=bar
  1105.  
  1106.     # make file descriptor 9 a duplicate of file descriptor 0 (stdin);
  1107.     # then connect stdin to /etc/passwd; the original stdin is now
  1108.     # `remembered' in file descriptor 9; see dup(2) and sh(1)
  1109.     exec 9<&0 < /etc/passwd
  1110.  
  1111.     while read line
  1112.     do
  1113.         # do something with $line
  1114.         foo=bletch
  1115.     done
  1116.  
  1117.     # make stdin a duplicate of file descriptor 9, i.e. reconnect it to
  1118.     # the original stdin; then close file descriptor 9
  1119.     exec 0<&9 9<&-
  1120.  
  1121.     echo "foo is now: $foo"
  1122.  
  1123.     This should always print ``foo is now: bletch''.
  1124.     Right, take the next example:
  1125.  
  1126.     foo=bar
  1127.  
  1128.     echo bletch | read foo
  1129.  
  1130.     echo "foo is now: $foo"
  1131.  
  1132.     This will print ``foo is now: bar'' in many implementations,
  1133.     ``foo is now: bletch'' in some others.  Why?
  1134.     Generally each part of a pipeline is run in a different subshell;
  1135.     in some implementations though, the last command in the pipeline is
  1136.     made an exception: if it is a builtin command like ``read'', the current
  1137.     shell will execute it, else another subshell is created.
  1138.  
  1139.     Draft 10 of POSIX 1003.2 allows both behaviours; future drafts may
  1140.     explicitly specify only one of them though.
  1141.  
  1142. 26) How do I use popen() to open a process for reading AND writing?
  1143.     
  1144.     The problem with trying to pipe both input and output to an arbitrary
  1145.     slave process is that deadlock can occur, if both processes are waiting
  1146.     for not-yet-generated input at the same time.  Deadlock can be avoided
  1147.     only by having BOTH sides follow a strict deadlock-free protocol, but
  1148.     since that requires cooperation from the processes it is inappropriate
  1149.     for a popen()-like library function.
  1150.  
  1151.     The 'expect' distribution includes a library of functions that a C
  1152.     programmer can call directly.  One of the functions does the
  1153.     equivalent of a popen for both reading and writing.  It uses ptys
  1154.     rather than pipes, and has no deadlock problem.  It's portable to
  1155.     both BSD and SV.  See the next answer for more about 'expect'.
  1156.  
  1157. 27) How do I run 'passwd', 'ftp', 'telnet', 'tip' and other interactive
  1158.     programs from a shell script or in the background?
  1159.  
  1160.     The shell itself cannot interact with interactive tty-based programs
  1161.     like these. Fortunately some programs have been written to manage
  1162.     the connection to a pseudo-tty so that you can run these sorts
  1163.     of programs in a script.
  1164.     
  1165.     'expect' is a one such program, which you can ftp pub/expect.shar.Z
  1166.     from durer.cme.nist.gov.
  1167.  
  1168.     The following expect script is an example of a non-interactive
  1169.     version of passwd(1).
  1170.  
  1171.         # username is passed as 1st arg, password as 2nd
  1172.         set password [index $argv 2]
  1173.         spawn passwd [index $argv 1]
  1174.         expect "*password:"
  1175.         send "$password\r"
  1176.         expect "*password:"
  1177.         send "$password\r"
  1178.         expect eof
  1179.  
  1180.     Another solution is provided by the 'pty' program, which runs a
  1181.     program under a pty session and was posted to comp.sources.unix,
  1182.     volume 23, issue 31.  You can also ftp pub/flat/pty-* from
  1183.     stealth.acf.nyu.edu .  A pty-based solution using named pipes
  1184.     to do the same as the above might look like this:
  1185.  
  1186.     #!/bin/sh
  1187.     /etc/mknod out.$$ p; exec 2>&1
  1188.     ( exec 4<out.$$; rm -f out.$$
  1189.     <&4 waitfor 'password:'
  1190.         echo "$2"
  1191.     <&4 waitfor 'password:'
  1192.         echo "$2"
  1193.     <&4 cat >/dev/null
  1194.     ) | ( pty passwd "$1" >out.$$ )
  1195.  
  1196.     Here, 'waitfor' is a simple C program that searches for
  1197.     its argument in the input, character by character.  You can
  1198.     ftp pub/flat/misc-waitfor.c from stealth.acf.nyu.edu .
  1199.  
  1200.     A simpler pty solution (which has the drawback of not 
  1201.     synchronizing properly with the passwd program) is
  1202.  
  1203.     #!/bin/sh
  1204.     ( sleep 5; echo "$2"; sleep 5; echo "$2") | pty passwd "$1"
  1205.  
  1206.  
  1207. 28) How do I sleep() in a C program for less than one second?
  1208.  
  1209.     The first thing you need to be aware of is that all you can specify is a
  1210.     MINIMUM amount of delay; the actual delay will depend on scheduling
  1211.     issues such as system load, and could be arbitrarily large if you're
  1212.     unlucky.
  1213.  
  1214.     There is no standard library function that you can count on in all
  1215.     environments for "napping" (the usual name for short sleeps).  The
  1216.     following code is adapted from Doug Gwyn's System V emulation
  1217.     support for 4BSD and exploits the 4BSD select() system call.  On
  1218.     System V you might be able to use poll() in a similar way.
  1219.  
  1220.     /*
  1221.         nap -- support routine for 4.2BSD system call emulations
  1222.  
  1223.         last edit:    29-Oct-1984    D A Gwyn
  1224.     */
  1225.  
  1226.     extern int    select();
  1227.  
  1228.  
  1229.     int
  1230.     nap( usec )                    /* returns 0 if ok, else -1 */
  1231.         long        usec;        /* delay in microseconds */
  1232.         {
  1233.         static struct            /* `timeval' */
  1234.             {
  1235.             long    tv_sec;        /* seconds */
  1236.             long    tv_usec;    /* microsecs */
  1237.             }    delay;        /* _select() timeout */
  1238.  
  1239.         delay.tv_sec = usec / 1000000L;
  1240.         delay.tv_usec = usec % 1000000L;
  1241.  
  1242.         return select( 0, (long *)0, (long *)0, (long *)0, &delay );
  1243.         }
  1244.  
  1245.  
  1246. 29) How can I get setuid shell scripts to work?
  1247.  
  1248.     [ This is a long answer, but it's a complicated and frequently-asked
  1249.       question.  Thanks to Maarten Litmaath for this answer, and
  1250.       for the "indir" program mentioned below. ]
  1251.  
  1252.     Let us first assume you are on a UNIX variant (e.g. 4.3BSD or SunOS)
  1253.     that knows about so-called `executable shell scripts'.  Such a script
  1254.     must start with a line like:
  1255.  
  1256.     #!/bin/sh
  1257.  
  1258.     The script is called `executable' because just like a real (binary)
  1259.     executable it starts with a so-called `magic number' indicating the
  1260.     type of the executable.  In our case this number is `#!' and the OS
  1261.     takes the rest of the first line as the interpreter for the script,
  1262.     possibly followed by 1 initial option like:
  1263.  
  1264.     #!/bin/sed -f
  1265.  
  1266.     Suppose this script is called `foo' and is found in /bin,
  1267.     then if you type:
  1268.  
  1269.     foo arg1 arg2 arg3
  1270.  
  1271.     the OS will rearrange things as though you had typed:
  1272.  
  1273.     /bin/sed -f /bin/foo arg1 arg2 arg3
  1274.  
  1275.     There is one difference though: if the setuid permission bit for
  1276.     `foo' is set, it will be honored in the first form of the command;
  1277.     if you really type the second form, the OS will honor the permission
  1278.     bits of /bin/sed, which is not setuid, of course.
  1279.  
  1280.     ----------
  1281.  
  1282.     OK, but what if my shell script does NOT start with such a `#!' line
  1283.     or my OS does not know about it?
  1284.  
  1285.     Well, if the shell (or anybody else) tries to execute it, the OS will
  1286.     return an error indication, as the file does not start with a valid
  1287.     magic number.  Upon receiving this indication the shell ASSUMES the
  1288.     file to be a shell script and gives it another try:
  1289.  
  1290.     /bin/sh shell_script arguments
  1291.  
  1292.     But we have already seen that a setuid bit on `shell_script' will NOT
  1293.     be honored in this case!
  1294.  
  1295.     ----------
  1296.  
  1297.     Right, but what about the security risks of setuid shell scripts?
  1298.  
  1299.     Well, suppose the script is called `/etc/setuid_script', starting
  1300.     with:
  1301.     
  1302.     #!/bin/sh
  1303.     
  1304.     Now let us see what happens if we issue the following commands:
  1305.  
  1306.     $ cd /tmp
  1307.     $ ln /etc/setuid_script -i
  1308.     $ PATH=.
  1309.     $ -i
  1310.  
  1311.     We know the last command will be rearranged to:
  1312.  
  1313.     /bin/sh -i
  1314.  
  1315.     But this command will give us an interactive shell, setuid to the
  1316.     owner of the script!
  1317.     Fortunately this security hole can easily be closed by making the
  1318.     first line:
  1319.  
  1320.     #!/bin/sh -
  1321.  
  1322.     The `-' signals the end of the option list: the next argument `-i'
  1323.     will be taken as the name of the file to read commands from, just
  1324.     like it should!
  1325.  
  1326.     ---------
  1327.  
  1328.     There are more serious problems though:
  1329.  
  1330.     $ cd /tmp
  1331.     $ ln /etc/setuid_script temp
  1332.     $ nice -20 temp &
  1333.     $ mv my_script temp
  1334.  
  1335.     The third command will be rearranged to:
  1336.  
  1337.     nice -20 /bin/sh - temp
  1338.  
  1339.     As this command runs so slowly, the fourth command might be able to
  1340.     replace the original `temp' with `my_script' BEFORE `temp' is opened
  1341.     by the shell!
  1342.     There are 4 ways to fix this security hole:
  1343.  
  1344.     1)  let the OS start setuid scripts in a different, secure way
  1345.         - System V R4 and 4.4BSD use the /dev/fd driver to pass the
  1346.         interpreter a file descriptor for the script
  1347.  
  1348.     2)  let the script be interpreted indirectly, through a frontend
  1349.         that makes sure everything is all right before starting the
  1350.         real interpreter - if you use the `indir' program from
  1351.         comp.sources.unix the setuid script will look like this:
  1352.  
  1353.         #!/bin/indir -u
  1354.         #?/bin/sh /etc/setuid_script
  1355.  
  1356.     3)  make a `binary wrapper': a real executable that is setuid and
  1357.         whose only task is to execute the interpreter with the name of
  1358.         the script as an argument
  1359.  
  1360.     4)  make a general `setuid script server' that tries to locate the
  1361.         requested `service' in a database of valid scripts and upon
  1362.         success will start the right interpreter with the right
  1363.         arguments.
  1364.  
  1365.     ---------
  1366.  
  1367.     Now that we have made sure the right file gets interpreted, are there
  1368.     any risks left?
  1369.  
  1370.     Certainly!  For shell scripts you must not forget to set the PATH
  1371.     variable to a safe path explicitly.  Can you figure out why?
  1372.     Also there is the IFS variable that might cause trouble if not set
  1373.     properly.  Other environment variables might turn out to compromise
  1374.     security as well, e.g. SHELL...
  1375.     Furthermore you must make sure the commands in the script do not
  1376.     allow interactive shell escapes!
  1377.     Then there is the umask which may have been set to something
  1378.     strange...
  1379.  
  1380.     Etcetera.  You should realise that a setuid script `inherits' all the
  1381.     bugs and security risks of the commands that it calls!
  1382.  
  1383.     All in all we get the impression setuid shell scripts are quite a
  1384.     risky business!  You may be better off writing a C program instead!
  1385.  
  1386. 30) What are some useful Unix or C books?
  1387.  
  1388.     Mitch Wright (mitch@hq.af.mil) maintains a useful list of Unix and
  1389.     C books, with descriptions and some mini-reviews.  There are currently
  1390.     77 titles on his list.
  1391.     
  1392.     You can obtain a copy of this list by anonymous ftp from
  1393.     iuvax.cs.indiana.edu (129.79.254.192), where it's
  1394.     "pub/Unix-C-Booklist".  If you can't use anonymous ftp, email the
  1395.     line "help" to "mailserv@iuvax.cs.indiana.edu" for instructions on
  1396.     retrieving things via email.
  1397.  
  1398.     Send additions or suggestions to mitch@hq.af.mil .
  1399.  
  1400. 31) How do I construct a shell glob-pattern that matches all files
  1401.     except "." and ".." ?
  1402.  
  1403.     You'd think this would be easy.
  1404.  
  1405.     *        Matches all files that don't begin with a ".";
  1406.  
  1407.     .*         Matches all files that do begin with a ".", but
  1408.          this includes the special entries "." and "..",
  1409.          which often you don't want;
  1410.  
  1411.     .[^.]*   (Newer shells only)  
  1412.          Matches all files that begin with a "." and are
  1413.          followed by a non-"."; unfortunately this will miss
  1414.          "..foo";
  1415.  
  1416.     .??*     Matches files that begin with a "." and which are
  1417.          at least 3 characters long.  This neatly avoids
  1418.          "." and "..", but also misses ".a" . 
  1419.  
  1420.     
  1421.     Many people are willing to use .??* to match all dotfiles
  1422.     (or * .??* to match all files) even though that pattern doesn't
  1423.     get everything - it has the advantage of being easy to type.
  1424.     If you really do want to be sure, you'll need to employ
  1425.     an external program or two and use backquote substitution.
  1426.     This is pretty good:
  1427.  
  1428.     `ls -a | sed -e '/^\.$/d' -e '/^\.\.$/d'`
  1429.  
  1430.     but even it will mess up on files with newlines in their names.
  1431.  
  1432. 32) How do I pronounce "vi" , or "!", or "/*", or ...?
  1433.  
  1434.     You can start a very long and pointless discussion by wondering
  1435.     about this topic on the net.  Some people say "vye", some say
  1436.     "vee-eye" (the vi manual suggests this) and some Roman numerologists
  1437.     say "six".  How you pronounce "vi" has nothing to do with whether
  1438.     or not you are a true Unix wizard.
  1439.  
  1440.     Similarly, you'll find that some people pronounce "char" as "care",
  1441.     and that there are lots of ways to say "#" or "/*" or "!" or
  1442.     "tty" or "/etc".  No one pronunciation is correct - enjoy the regional
  1443.     dialects and accents.  
  1444.  
  1445.     Since this topic keeps coming up on the net, here is a comprehensive
  1446.     pronunciation list that has made the rounds.  Send updates to
  1447.     Steve Hayman, sahayman@cs.indiana.edu.  Special thanks to Maarten
  1448.     Litmaath for his work in maintaining this list in the past.
  1449.  
  1450.             The Pronunciation Guide
  1451.             -----------------------
  1452.                   version 2.4
  1453.  
  1454. Names derived from UNIX are marked with *, names derived from C are marked
  1455. with +, names derived from (Net)Hack are marked with & and names deserving
  1456. futher explanation are marked with a #.  The explanations will be given at
  1457. the very end.
  1458.  
  1459. ------------------------------------------------------------------------------
  1460.                -- SINGLE CHARACTERS --
  1461.  
  1462.      SPACE, blank, ghost&
  1463.  
  1464. !    EXCLAMATION POINT, exclamation (mark), (ex)clam, excl, wow, hey, boing,
  1465.     bang#, shout, yell, shriek, pling, factorial, ball-bat, smash, cuss,
  1466.     store#, potion&, not*+, dammit*#
  1467.  
  1468. "    QUOTATION MARK, (double) quote, dirk, literal mark, rabbit ears,
  1469.     double ping, double glitch, amulet&, web&, inverted commas
  1470.  
  1471. #    CROSSHATCH, pound, pound sign, number, number sign, sharp, octothorpe#,
  1472.     hash, (garden) fence, crunch, mesh, hex, flash, grid, pig-pen,
  1473.     tictactoe, scratch (mark), (garden) gate, hak, oof, rake, sink&,
  1474.     corridor&, unequal#, punch mark
  1475.  
  1476. $    DOLLAR SIGN, dollar, cash, currency symbol, buck, string#, escape#, 
  1477.     ding, big-money, gold&, Sonne#
  1478.  
  1479. %    PERCENT SIGN, percent, mod+, shift-5, double-oh-seven, grapes, food&
  1480.  
  1481. &    AMPERSAND, and, amper, address+, shift-7, andpersand, snowman,
  1482.     bitand+, donald duck#, daemon&, background*, pretzel
  1483.  
  1484. '    APOSTROPHE, (single) quote, tick, prime, irk, pop, spark, glitch,
  1485.     lurker above&
  1486.  
  1487. *    ASTERISK, star, splat, spider, aster, times, wildcard*, gear, dingle,
  1488.     (Nathan) Hale#, bug, gem&, twinkle, funny button#, pine cone, glob*
  1489.  
  1490. ()   PARENTHESES, parens, round brackets, bananas, ears, bowlegs
  1491. (    LEFT PARENTHESIS,  (open) paren,  so,  wane,  parenthesee,   open,  sad,
  1492.     tool&
  1493. )    RIGHT PARENTHESIS, already, wax, unparenthesee, close (paren), happy,
  1494.     thesis, weapon&
  1495.  
  1496. +    PLUS SIGN, plus, add, cross, and, intersection, door&, spellbook&
  1497.  
  1498. ,    COMMA, tail, trapper&
  1499.  
  1500. -    HYPHEN, minus (sign), dash, dak, option, flag, negative (sign), worm,
  1501.     bithorpe#
  1502.  
  1503. .    PERIOD, dot, decimal (point), (radix) point, spot, full stop,
  1504.     put#, floor&
  1505.  
  1506. /    SLASH, stroke, virgule, solidus, slant, diagonal, over, slat, slak,
  1507.     across#, compress#, reduce#, replicate#, spare, divided-by, wand&,
  1508.     forward slash, shilling#
  1509.  
  1510. :    COLON, two-spot, double dot, dots, chameleon&
  1511.  
  1512. ;    SEMICOLON, semi, hybrid, giant eel&, go-on#
  1513.  
  1514. <>   ANGLE BRACKETS, angles, funnels, brokets, pointy brackets, widgets
  1515. <    LESS THAN,    less, read from*, from*,        in*,  comesfrom*, crunch,
  1516.     sucks, left chevron#, open pointy (brack[et]), bra#, upstairs&, west,
  1517.     (left|open) widget
  1518. >    GREATER THAN, more, write to*,  into/toward*, out*, gazinta*,   zap,
  1519.     blows, right chevron#, closing pointy (brack[et]), ket#, downstairs&,
  1520.     east, (right|close) widget
  1521.  
  1522. =    EQUAL SIGN, equal(s), gets, becomes, quadrathorpe#, half-mesh, ring&
  1523.  
  1524. ?    QUESTION MARK, question, query, whatmark, what, wildchar*, huh, ques,
  1525.     kwes, quiz, quark, hook, scroll&, interrogation point
  1526.  
  1527. @    AT SIGN, at, each, vortex, whirl, whirlpool, cyclone, snail, ape (tail),
  1528.     cat, snable-a#, trunk-a#, rose, cabbage, Mercantile symbol, strudel#,
  1529.     fetch#, shopkeeper&, human&, commercial-at, monkey (tail)
  1530.  
  1531. []   BRACKETS, square brackets, U-turns, edged parentheses
  1532. [    LEFT BRACKET,  bracket,   bra, (left) square (brack[et]),   opensquare,
  1533.     armor&
  1534. ]    RIGHT BRACKET, unbracket, ket, right square (brack[et]), unsquare, close,
  1535.     mimic&
  1536.  
  1537. \    BACKSLASH, reversed virgule, bash, (back)slant, backwhack, backslat,
  1538.     escape*, backslak, bak, scan#, expand#, opulent throne&, slosh, slope,
  1539.     blash
  1540.  
  1541. ^    CIRCUMFLEX, caret, carrot, (top)hat, cap, uphat, party hat, housetop, 
  1542.     up arrow, control, boink, chevron, hiccup, power, to-the(-power), fang,
  1543.     sharkfin, and#, xor+, wok, trap&, pointer#, pipe*, upper-than#
  1544.  
  1545. _    UNDERSCORE, underline, underbar, under, score, backarrow, flatworm, blank,
  1546.     chain&, gets#, dash#, sneak
  1547.  
  1548. `    GRAVE, (grave/acute) accent, backquote, left/open quote, backprime, 
  1549.     unapostrophe, backspark, birk, blugle, backtick, push, backglitch,
  1550.     backping, execute#, boulder&, rock&
  1551.  
  1552. {}   BRACES, curly braces, squiggly braces, curly brackets, squiggle brackets,
  1553.     Tuborgs#, ponds, curly chevrons#, squirrly braces, hitchcocks#,
  1554.     chippendale brackets#
  1555. {    LEFT BRACE,  brace,   curly,   leftit, embrace,  openbrace, begin+,
  1556.     fountain&
  1557. }    RIGHT BRACE, unbrace, uncurly, rytit,  bracelet, close,     end+, a pool&
  1558.  
  1559. |    VERTICAL BAR, pipe*, pipe to*, vertical line, broken line#, bar, or+,
  1560.     bitor+, vert, v-bar, spike, to*, gazinta*, thru*, pipesinta*, tube,
  1561.     mark, whack, gutter, wall&
  1562.  
  1563. ~    TILDE, twiddle, tilda, tildee, wave, squiggle, swung dash, approx, 
  1564.     wiggle, enyay#, home*, worm, not+
  1565.  
  1566.  
  1567.             -- MULTIPLE CHARACTER STRINGS --
  1568.  
  1569. !?    interrobang (one overlapped character)
  1570. */    asterslash+, times-div#
  1571. /*       slashterix+, slashaster
  1572. :=    becomes#
  1573. <-    gets
  1574. <<    left-shift+, double smaller
  1575. <>    unequal#
  1576. >>    appends*, cat-astrophe, right-shift+, double greater
  1577. ->    arrow+, pointer to+, hiccup+
  1578. #!    sh'bang, wallop
  1579. \!*    bash-bang-splat
  1580. ()    nil#
  1581. &&    and+, and-and+, amper-amper, succeeds-then*
  1582. ||    or+, or-or+, fails-then*
  1583.  
  1584.  
  1585.                 -- NOTES --
  1586.  
  1587. ! bang        comes from old card punch phenom where punching ! code made a
  1588.         loud noise; however, this pronunciation is used in the (non-
  1589.         computerized) publishing and typesetting industry in the U.S.
  1590.         too, so ...
  1591.         Alternatively it could have come from comic books, where the
  1592.         words each character utters are shown in a "balloon" near that
  1593.         character's head.  When one character shoots another, it is
  1594.         common to see a balloon pointing at the barrel of the gun to
  1595.         denote that the gun had been fired, not merely aimed. 
  1596.         That balloon contained the word "!" -- hence, "!" == "Bang!" 
  1597. ! store        from FORTH
  1598. ! dammit    as in "quit, dammit!" while exiting vi and hoping one hasn't
  1599.         clobbered a file too badly
  1600. # octothorpe    from Bell System (orig. octalthorpe)
  1601. # unequal    e.g. Modula-2
  1602. $ string    from BASIC
  1603. $ escape    from TOPS-10
  1604. $ Sonne        In the "socialist" countries they used and are using all kinds
  1605.         of IBM clones (hardware + sw). It was a common practice just
  1606.         to rename everything (IBM 360 --> ESER 1040 etc.).
  1607.         Of course the "dollar" sign had to be renamed - it became the
  1608.         "international currency symbol" which looks like a circle with
  1609.         4 rays spreading from it:
  1610.               ____
  1611.             \/    \/
  1612.             /      \
  1613.             \      /
  1614.             /\____/\
  1615.  
  1616.         Because it looks like a (small) shining sun, in the German
  1617.         Democratic Republic it was usually called "Sonne" (sun).
  1618. & donald duck    from the Danish "Anders And", which means "Donald Duck"
  1619. * splat        from DEC "spider" glyph
  1620. * Nathan Hale    "I have but one asterisk for my country."
  1621. * funny button    at Pacific Bell, * was referred to by employees as the "funny
  1622.         button", which did not please management at all when it became
  1623.         part of the corporate logo of Pacific Telesis, the holding
  1624.         company ...
  1625. */ times-div    from FORTH
  1626. = quadrathorpe    half an octothorpe
  1627. - bithorpe    half a quadrathorpe (So what's a monothorpe?)
  1628. . put        Victor Borge's Phonetic Punctuation which dates back to the
  1629.         middle 1950's
  1630. / across    APL
  1631. / compress    APL
  1632. / reduce    APL
  1633. / replicate    APL
  1634. / shilling    from the British currency symbol
  1635. := becomes    e.g. Pascal
  1636. ; go-on        Algol68
  1637. < left chevron    from the military: worn vertically on the sleeve to signify
  1638.         rating
  1639. < bra        from quantum mechanics
  1640. <> unequal    e.g. Pascal
  1641. > right chevron    see "< left chevron"
  1642. > ket        from quantum mechanics
  1643. @ snable-a    from Danish; may translate as "trunk-a"
  1644. @ trunk-a    "trunk" = "elephant nose"
  1645. @ strudel    as in Austrian apple cake
  1646. @ fetch        from FORTH
  1647. \ scan        APL
  1648. \ expand    APL
  1649. ^ and        from formal logic
  1650. ^ pointer    from PASCAL
  1651. ^ upper-than    cf. > and <
  1652. _ gets        some alternative representation of underscore resembles a
  1653.         backarrow
  1654. _ dash        as distinct from '-' == minus
  1655. ` execute    from shell command substitution
  1656. {} Tuborgs    from advertizing for well-known Danish beverage
  1657. {} curly chevr.    see "< left chevron"
  1658. {} hitchcocks    from the old Alfred Hitchcock show, with the stylized profile
  1659.         of the man
  1660. {} chipp. br.    after Chippendale chairs
  1661. | broken line    EBCDIC has two vertical bars, one solid and one broken.
  1662. ~ enyay        from the Spanish n-tilde
  1663. () nil        LISP
  1664. -- 
  1665. Steve Hayman    Workstation Manager    Computer Science Department   Indiana U.
  1666. sahayman@iuvax.cs.indiana.edu                                    (812) 855-6984
  1667. NeXT Mail: sahayman@spurge.bloomington.in.us
  1668.