Wednesday, November 16, 2005

Variables

If it's a programming language, it needs variables. Here's how you assign a value to a shell variable, and how you get that value back (dereference it).

#!/bin/bash

# Here's how
# you give variables values.

HELLO="hello, world"

# (No spaces allowed around the '=' sign:
# a design botch in the shell.)

# And here's how you use them. Note the dollar sign.

echo $HELLO

Convince yourself that this works interactively, too. Try putting spaces around the equals sign, to see what the error message says. That way, when you make this mistake, you'll recognize it.

I don't know anyone who's crazy about this design (no spaces, '$' to dereference, no '$' to set), but we can no more fix it now than we can fix English syntax. There may be shell scripts still running that were written before you were born. Hindsight's always 20-20.

Unsurprisingly, you can also assign variables the values of other variables. This is a programming language.

GOODBYE=$HELLO
echo $GOODBYE
echo $HELLO

You can also unset a variable.
    
unset HELLO
echo $GOODBYE
echo $HELLO

0 Comments:

Post a Comment

<< Home