tags:

views:

57

answers:

4

I am trying to learn shell scripting and I am kind of confused with the idea of := or default value

#!/bin/sh                                                                                                                             

echo "Please enter a number \c"
read input
input=$((input % 2))

if [ $input -eq 0 ]
then
    echo "The number is even"
else
    echo "The number is odd"
fi

echo "Beginning of second part"
a="BLA" 
a="Dennis"
echo $a
unset a
echo "a after unsetting"
echo $a
${a:=HI}
echo "unsetting a again"
unset a
echo $a

And I get this

Dennis
a after unsetting

./ifstatement.sh: line 21: HI: command not found
unsetting a again
A: 

${a:=HI} expands to HI, which your shell then tries to run as a command. If you're just trying to set the value of a variable if it is not set, you may want to do something like [ -z "$b" ] && b=BYE

cam
i actually want to set a default value in a variable so that if i unset it the default variable will show up
denniss
Hmm, that's not what := does. := just expands to the value on the right if the left is not defined. It would be like `"#{a || 'HI'}"` in ruby
cam
A: 

Instead of calling unset $a, you do ${a:=HI} again

ghostdog74
isnt that the purpose of setting a default value though? once you unset a variable and you echo it, the default value should show up.
denniss
That's because when you unset, you are removing the variable.
ghostdog74
+5  A: 

When you write

${a:=HI}

the shell splits the result of the expansion into words, and interprets the first word as a command, as it would for any command line.

Instead, write

: "${a:=HI}"

: is a no-op command. The quotes prevent the shell from trying to do globbing, which in rare circumstances could cause a slowdown or an error.

Gilles
+1  A: 

There isn't a way to set a value that a variable will always "fall back" to when you un-set it. When you use the unset command, you are removing the variable (not just clearing the value associated with it) so it can't have any value, default or otherwise.

Instead, try a combination of two things. First, make sure the variable gets initialized. Second, create a function that sets the variable to the desired default value. Call this variable instead of unset. With this combination, you can simulate a variable having a "default" value.

bta
that explains everything. thank you very much.
denniss