home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Unix Power ToolsUnix Power ToolsSearch this book

29.9. How to Put if-then-else in a C-Shell Alias

The C shell's brain damage keeps you from using an if with an else in an alias. You have to use a sourceable script (Section 29.7). Or that's what I thought until I saw an article by Lloyd Zusman on comp.unix.questions in December 1987. He'd saved an earlier posting on that group (but without its author's name) that showed how. The trick: use enough backslashes (\) and the eval (Section 27.8) command.

As an example, here's an alias named C for compiling C programs. It needs the executable filename (like C prog), not the source filename (like C prog.c). If you type a filename ending in .c, it complains and quits. Else, it does the following:

  • Renames any old prog file to prog.old.

  • Prints the message prog SENT TO cc.

  • Compiles prog.c.

  • And -- if there's a prog file (if the compile succeeded) -- runs chmod 311 prog to protect the file from accidental reading with a command like cat * or more *.

Your alias doesn't need to be as complicated. But this one shows some tricks, such as putting an if inside the if, that you might want to use. Watch your quoting -- remember that the shell strips off one level of quoting when you set the alias (Section 29.3) and another during the first pass of the eval. Follow this example and you'll probably be fine:

Figure Go to http://examples.oreilly.com/upt3 for more information on: if-else-alias.cs

# COMPILE AND chmod C PROGRAMS; DON'T USE .c ON END OF FILENAME.
alias C 'eval "if (\!* =~ *.c) then \\
   echo "C quitting: no .c on end of \!* please." \\
else \\
   if (-e \!*) mv \!* \!*.old \\
   echo \!*.c SENT TO cc \\
   cc -s \!*.c -o \!* \\
   if (-e \!*) chmod 311 \!* \\
endif"'

-- JP



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.