Thursday, November 17, 2005

Control Flow: Conditionals

Real programming languages also have control flow constructs, like conditionals and loops. Here's a conditional
#!/bin/bash

# Some variables are built in, and predefined.
# $0 is C's argv[0], or Perl's $0

# $1, $2, etc., are the rest of argv[]/$ARGV
# $* is the whole arg list

# You can even use "test" to test the value of variables

if test "$*" = ""
then
HELLO="hello, world"
else
HELLO="hello $*"
fi

echo $HELLO

As usual, snarf-n-barf this into a file -- call it hello -- make it executable, and run it. Try it both as hello and as hello $LOGNAME .

Try typing this program interactively to see how the interactive shell handles control-flow statements. Watch the prompt change. What's $* for your interactive shell? (Hint: echo $*).

But would anyone use an if ... then ... else ... or even an if ... then ... on the command line? Daily. I'll show practical examples, and some other useful forms for conditionals, too.

(The Boehm-Jacopini theorem says a programming language needs nothing but a "while" and an "if," but language designers know enough not to leave well enough alone. I could write this blog in Basic English, but why would I want to?)

Next up, loops.

0 Comments:

Post a Comment

<< Home