Berkeley CSUA MOTD:Entry 43168
Berkeley CSUA MOTD
 
WIKI | FAQ | Tech FAQ
http://csua.com/feed/
2025/05/25 [General] UID:1000 Activity:popular
5/25    

2006/5/23-28 [Computer/SW/Languages/Perl, Computer/SW/Unix] UID:43168 Activity:nil
5/23    I'm trying to learn sh, bash, and csh programming. What's a good
        site that has sample syntax of the following ***psuedocode*** for
        each of the shells?
        foreach $file in (<dir/*>) do;
          echo I have file $file
        done;
        switch ($var) {
          case 0: echo hello; break;    // this is a comment
          default: echo default; break;
        }
        if ($z>=5 || $str eq '12345) {print $hello}
        \_ not really.  I'll start w/ sh:  --dbushong
           for file in dir/*; do
             echo I have file $file
           done
           case "$var" in
             0)
               echo hello
               ;;
             *)
               echo default
               ;;
           esac
           if [ $z -ge 5 -o $str = 12345 ]; then
             echo $hello
           fi
        \_ bash is basically a superset of sh.  Whenever I need to brush up
           I usually just google for shell scripting, and frequently
           (re)discover this site:
           http://vertigo.hsrl.rutgers.edu/ug/shell_help.html
           Incidentally, csh is a great interactive shell, but there are some
           compelling arguments why you may want to avoid it for general
           scripting purposes (of course, one nerd's compelling arguments are
           another nerds religious claptrap so ymmv):
           http://www.faqs.org/faqs/unix-faq/shell/csh-whynot
           Also, I find the O'Reilly UNIX Power Tools book to be a very useful
           reference to have around when shell scripting. -dans
        \_ I gave up on csh for all but the simplest shell scripting when
           I noticed it didn't handle nested if/then cases sanely, and went
           through coding hell trying to workaround it.  If you're
           going anything more than 2-3 lines, use a sh based shell, or
           a "real" script language like perl. -ERic
           \_ I'll second that.  I still use tcsh from the cmd line just because
              I find it more pleasant than bash, but meh.  I'll tend to use
              perl unless the script is going to end up being more than about
              25% program executions.  --dbushong
           \_ My rule is 10 lines.  If I can't write it in 10 lines of some
              shell script language in a few minutes I'll use perl instead.
ERROR, url_link recursive (eces.Colorado.EDU/secure/mindterm2) 2025/05/25 [General] UID:1000 Activity:popular
5/25    

You may also be interested in these entries...
2012/8/29-11/7 [Computer/SW/Security] UID:54467 Activity:nil
8/29    There was once a CSUA web page which runs an SSH client for logging
        on to soda.  Does that page still exist?  Can someone remind me of the
        URL please?  Thx.
        \_ what do you mean? instruction on how to ssh into soda?
           \_ No I think he means the ssh applet, which, iirc, was an applet
              that implemented an ssh v1 client.  I think this page went away
	...
2012/9/20-11/7 [Computer/SW/Unix, Finance/Investment] UID:54482 Activity:nil
9/20    How do I change my shell? chsh says "Cannot change ID to root."
        \_ /usr/bin/chsh does not have the SUID permission set. Without
           being set, it does not successfully change a user's shell.
           Typical newbie sys admin (on soda)
           \_ Actually, it does: -rwsr-xr-x 1 root root 37552 Feb 15  2011 /usr/bin/chsh
	...
2012/9/24-11/7 [Computer/SW/Languages, Computer/SW/Unix] UID:54484 Activity:nil
9/24    How come changing my shell using ldapmodify (chsh doesn't work) doesn't
        work either? ldapsearch and getent show the new shell but I still get
        the old shell on login.
        \_ Scratch that, it magically took my new shell now. WTF?
           \_ probably nscd(8)
	...
2012/3/29-6/4 [Computer/HW/Memory, Computer/HW/CPU, Computer/HW/Drives] UID:54351 Activity:nil
3/29    A friend wants a PC (no mac). She doesn't want Dell. Is there a
        good place that can custom build for you (SSD, large RAM, cheap video
        card--no game)?
        \_ As a side note: back in my Cal days more than two decades ago when
           having a 387SX made me the only person with floating-point hardware,
           most machines were custom built.
	...
2012/4/27-6/4 [Computer/SW/Languages/Misc, Computer/SW/Unix] UID:54372 Activity:nil
4/27    I wrote a little shell script to collect iostat data:
        #!/bin/bash
        DATE=`date +%m%d`
        DATADIR=/var/tmp/user
        OUTPUTFILE=$DATADIR/$DATE.out
        while true
	...
2012/1/27-3/26 [Computer/SW/Unix] UID:54299 Activity:nil
1/27    Interesting list of useful unix tools. Shout out to
        cowsay even!
        http://www.stumbleupon.com/su/3428AB/kkovacs.eu/cool-but-obscure-unix-tools
        \_ This is nice.  Thanks.
	...
2011/10/26-12/6 [Computer/SW/Unix] UID:54202 Activity:nil
10/24  What's an easy way to see if say column 3 of a file matches a list of
       expressions in a file? Basically I want to combine "grep -f <file>"
       to store the patterns and awk's $3 ~ /(AAA|BBB|CCC)/ ... I realize
       I can do this with "egrep -f " and use regexp instead of strings, but
       was wondering if there was some magic way to do this.
       \_ UNIX has no magic. Make a shell script to produce the ask or egrep
	...
2011/5/19-7/13 [Computer/SW/Languages/Misc] UID:54115 Activity:nil
5/19    If script A runs, and calls script B ..... is it possible for me to exit\
        script A based on results of script B and not continue?
        \_ assume any shell
        \_ Yes.
           \_ without passing the result to some stupid temp file?
              \_ It sounds like you want "scriptb || exit", which will run
	...
Cache (3869 bytes)
vertigo.hsrl.rutgers.edu/ug/shell_help.html
How to write a shell script Introduction A shell is a command line interpretor. Creating a Script Suppose you often type the command find . ", is the name of a program which should be used to interpret the contents of the file. Long ago there was just one (the Bourne Shell) but these days there are many interpretors -- Csh, Ksh, Bash, and others. Comments Comments are any text beginning with the pound sign. A comment can start anywhere on a line and continue until the end of the line. Search Path All shell scripts should include a search path specifica- tion: PATH=/usr/ucb:/usr/bin:/bin; export PATH A PATH specification is recommended -- often times a script will fail for some people because they have a different or incomplete search path. The Bourne Shell does not export environment variables to children unless explicitly instructed to do so by using the export command. Argument Checking A good shell script should verify that the arguments sup- plied (if any) are correct. On BSD systems there's been an attempt to categorize some of the more common exit status codes. See /usr/include/sysexitsh Using exit status Exit codes are important for those who use your code. then echo Enter text end with \^D fi Your code should be written with the expectation that others will use it. Making sure you return a meaningful exit status will help. Stdin, Stdout, Stderr Standard input, output, and error are file descriptors 0, 1, and 2 Each has a particular role and should be used accordingly: # is the year out of range for me? As for input/output dialogue: # give the fellow a chance to quit if tty -s ; if the standard input is a tty rather than a pipe, or file, or etc. Language Constructs For loop iteration Substitute values for variable and perform task: for variable in word ... To get the contents of a variable you must prepend the name with a $. echo $1) + Exporting Variables Variables are not exported to children unless explicitly marked. export POSTSCRIPT ${variable:-word} If the variable has been set and is not null, use it's value, else use word. These are useful constructions for honoring the user envi- ronment. the user of the script can override variable assignments. programs like lpr honor the PRINTER environment variable, you can do the same trick with your shell scripts. word} If variable is set use it's value, else print out word and exit. And, some commands: shift Shift the postional variables down one and decrement number of arguments. esac shift done A use of the set command: # figure out what day it is TODAY=(set \date\; tmp=/tmp/cal0$$ trap "rm -f $tmp /tmp/cal1$$ /tmp/cal2$$" trap exit 1 2 13 15 /usr/lib/calprog >$tmp $? fi * Quotes/Special Characters Special characters to terminate words: ; To quote any of these use a backslash or bracket with quote marks ("" or ''). Single Quotes Within single quotes all characters are quoted -- including the backslash. grep :${gid}: /etc/group | awk -F: '{print $1}' Double Quotes Within double quotes you have variable subsitution (ie. the dollar sign is interpreted) but no file name generation (ie. are the arguments to the function (not the arguments to the script). For example: # deal with a file, add people one at a time do_file() { while parse_one etc... A couple of choices: sh command This runs the shell script as a separate shell. command This runs the shell script from within the current shell script. The second form is useful for configuration files where environment variable are set for the script. The Unix tradition is that programs should execute as qui- etly as possible. then echo Enter text end with \^D fi The tradition also extends to output. then echo Enter text end with \^D >&0 fi Have you ever had a program stop waiting for keyboard input when the output is directed elsewhere? For example: # take standard input (or a specified file) and do it.
Cache (8165 bytes)
www.faqs.org/faqs/unix-faq/shell/csh-whynot -> www.faqs.org/faqs/unix-faq/shell/csh-whynot/
I am continually shocked and dismayed to see people write test cases, install scripts, and other random hackery using the csh. The csh is seductive because the conditionals are more C-like, so the path of least resistance is chosen and a csh script is written. Sadly, this is a lost cause, and the programmer seldom even realizes it, even when they find that many simple things they wish to do range from cumbersome to impossible in the csh. FILE DESCRIPTORS The most common problem encountered in csh programming is that you can't do file-descriptor manipulation. All you are able to do is redirect stdin, or stdout, or dup stderr into stdout. Bourne-compatible shells offer you an abundance of more exotic possibilities. Writing Files In the Bourne shell, you can open or dup arbitrary file descriptors. Or what if you just want to throw away stderr and leave stdout alone? In the csh, you can only make a pitiful attempt like this: (cmd > /dev/tty) >& /dev/null But who said that stdout was my tty? Along these same lines, you can't direct error messages in csh scripts out stderr as is considered proper. In the Bourne shell, you might say: echo "$0: cannot find $file" 1>&2 but in the csh, you can't redirect stdout out stderr, so you end up doing something silly like this: sh -c 'echo "$0: cannot find $file" 1>&2' 1b. Reading Files In the csh, all you've got is $<, which reads a line from your tty. Tough noogies, you still get your tty, which you really can't redirect. Now, the read statement in the Bourne shell allows you to read from stdin, which catches redirection. It also means that you can do things like this: exec 3<file1 exec 4<file2 Now you can read from fd 3 and get lines from file1, or from file2 through fd 4. In modern, Bourne-like shells, this suffices: read some_var 0<&3 read another_var 0<&4 Although in older ones where read only goes from 0, you trick it: exec 5<&0 # save old stdin exec 0<&3; Closing FDs In the Bourne shell, you can close file descriptors you don't want open, like 2>&-, which isn't the same as redirecting it to /dev/null. More Elaborate Combinations Maybe you want to pipe stderr to a command and leave stdout alone. In a Bourne shell, you can do things like this: exec 3>&1; The closes there were in case something really cared about all its FDs. But if you want it from A, you're out of luck -- if you're in the csh, that is. In the Bourne shell, you can get it, although doing so is a bit tricky. Here's something I had to do where I ran dd's stderr into a grep -v pipe to get rid of the records in/out noise, but had to return the dd's exit status, not the grep's: device=/dev/rmt8 dd_noise='^ 0-9 +\+ 0-9 + records (in|out)$' exec 3>&1 status=((dd if=$device ibs=64k 2>&1 1>&3 3>&- 4>&-; Even simple little things like this: % time | echo which while nonsensical, shouldn't give me this message: Reset tty pgrp from 9341 to 26678 Others are more fun: % sleep 1 | while while: Too few arguments. White space can matter: if(expr) may fail on some versions of csh, while if (expr) works! Your vendor may have attempted to fix this bug, but odds are good that their csh still won't be able to handle if then if then echo A: got here else echo B: got here endif echo We should never execute this statement endif 3. SIGNALS In the csh, all you can do with signals is trap SIGINT. In the Bourne shell, you can trap any signal, or the end-of-program exit. For example, to blow away a tempfile on any of a variety of signals: $ trap 'rm -f /usr/adm/tmp/i$$ ; This makes it really hard to construct strings with mixed quotes in them. You have to use backslashes for newlines, and it's just darn hard to get them into strings sometimes. VARIABLE SYNTAX There's this big difference between global (environment) and local (shell) variables. In csh, you use a totally different syntax to set one from the other. In the Bourne shell, this VAR=foo cmds args is the same as (export VAR; Watch: echo Try testing with $SHELL:t It's really nice to be able to say ${PAGER-more} or FOO=${BAR:-${BAZ}} to be able to run the user's PAGER if set, and more otherwise. You can't get the process number of the last background command from the csh, something you might like to do if you're starting up several jobs in the background. The csh is also flaky about what it does when it imports an environment variable into a local shell variable, as it does with HOME, USER, PATH, and TERM. Consider this: % setenv TERM '/bin/ls -l / > /dev/tty' % csh -f And watch the fun! MANPAGER) setenv PAGER $MANPAGER Despite your attempts to only set PAGER when you want to, the csh aborts: MANPAGER: Undefined variable. That's because it parses the whole line anyway AND EVALUATES IT! X && $X == 'foo') echo ok X: Undefined variable This forces you to write a couple nested if statements. This is highly undesirable because it renders short-circuit booleans useless in situations like these. If the csh were the really C-like, you would expect to be able to safely employ this kind of logic. Consider the common C construct: if (p && p->member) Undefined variables are not fatal errors in the Bourne shell, so this issue does not arise there. While the csh does have built-in expression handling, it's not what you might think. This is an error @ a = 4/2 but this is ok @ a = 4 / 2 The ad hoc parsing csh employs fouls you up in other places as well. ERROR HANDLING Wouldn't it be nice to know you had an error in your script before you ran it? This is especially good to make sure seldom taken segments of code code are correct. Consider this statement: exit Of course, they really meant exit or just exit 1 Either shell will complain about this. If you have an alias with backquotes, and use that in backquotes in another one, you get a coredump. Here's another one: % mkdir tst % cd tst % touch ' foo bar' % foreach var ( * ) > echo "File named $var" > end foreach: No match. SUMMARY While some vendors have fixed some of the csh's bugs (the tcsh also does much better here), many have added new ones. Most of its problems can never be solved because they're not actually bugs per se, but rather the direct consequences of braindead design decisions. Do yourself a favor, and if you *have* to write a shell script, do it in the Bourne shell. The Korn shell is the preferred programming shell by many sh addicts, but it still suffers from inherent problems in the Bourne shell's design, such as parsing and evaluation horrors. The Korn shell or its public-domain clones and supersets (like bash) aren't quite so ubiquitous as sh, so it probably wouldn't be wise to write a sharchive in them that you post to the net. Until then, we'll be stuck with bug-incompatible versions of the sh lying about. The Plan 9 shell, rc, is much cleaner in its parsing and evaluation; If you don't have to use a shell, but just want an interpreted language, many other free possibilities present themselves, like Perl, REXX, TCL, Scheme, or Python. Of these, Perl is probably the most widely available on UNIX (and many other) systems and certainly comes with the most extensive UNIX interface. Increasing numbers vendors ship Perl with their standard systems. You can get at networking functions, binary data, and most of the C library. There are also translators to turn your sed and awk scripts into Perl scripts, as well as a symbolic debugger. Tchrist's personal rule of thumb is that if it's the size that fits in a Makefile, it gets written in the Bourne shell, but anything bigger gets written in Perl. He calls it 'csh' or the 'hamilton csh', but it's not a csh as it's neither bug nor feature compatible with the real csh. Actually, he's fixed a great deal, but in doing so, has created a totally different shell. Vote 16 Current Top-Rated FAQs Are you an expert in this area? Share your knowledge and earn expert points by giving answers or rating people's questions and answers! ORG is not sanctioned in any way by FAQ authors or maintainers. Questions strongly related to this FAQ: * 17 i want to get some exmaples of shell programming i mean the problems by Puneet (2/14/2004) * 18 hi all, i need to write a csh script in which i run a perl script.