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

UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 10.6 Avoiding C Shell Alias Loops Chapter 10
Aliases
Next: 10.8 Fix Quoting in csh Aliases with makealias and quote
 

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

The C shell's brain damage (47.2 ) keeps you from using an if (47.3 ) with an else in an alias. You have to use a sourceable script (10.5 ) . 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 (8.10 ) command.

As an example, here's an alias named C for compiling (52.8 ) 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:

  • 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, like putting an if inside the if , that you might want to use. The expressions like =~ and -e are explained in article 47.4 . Watch your quoting - remember that the shell strips off one level of quoting when you set the alias (10.3 ) and another during the first pass of the eval . Follow this example and you'll probably be fine:


# 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


Previous: 10.6 Avoiding C Shell Alias Loops UNIX Power Tools Next: 10.8 Fix Quoting in csh Aliases with makealias and quote
10.6 Avoiding C Shell Alias Loops Book Index 10.8 Fix Quoting in csh Aliases with makealias and quote

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System










??????????????@Mail.ru