4

Here's a simple version of my script which displays the failure:

#!/bin/bash
${something:="false"}
${something_else:="blahblah"}
${name:="file.ext"}

echo ${something}
echo ${something_else}
echo ${name}

When I echo the variables, I get the values I put in, but it also emits an error. What am I doing wrong?

Output:

./test.sh: line 3: blahblah: command not found
./test.sh: line 4: file.ext: command not found
false
blahblah
file.ext

The first two lines are being emitted to stderr, while the next three are being output to stdout.

My platform is fedora 15, bash version 4.2.10.

3 Answers 3

6

You can add colon:

: ${something:="false"}
: ${something_else:="blahblah"}
: ${name:="file.ext"}

The trick with a ":" (no-operation command) is that, nothing gets executated, but parameters gets expanded. Personally I don't like this syntax, because for people not knowing this trick the code is difficult to understand.

You can use this as an alternative:

something=${something:-"default value"}

or longer, more portable (but IMHO more readable):

[ "$something" ] || something="default value"
Sign up to request clarification or add additional context in comments.

2 Comments

Huh, I did a quick man : and I think the : will do what I like. I'll make sure to comment this thoroughly though. Are there any better alternatives?
the ":" is a builtin. You need to "help :" or "man bash". See "SHELL BUILTIN COMMANDS" section.
3

Putting a variable on a line by itself will execute the command stored in the variable. That an assignment is being performed at the same time is incidental.

In short, don't do that.

echo ${something:="false"}
echo ${something_else:="blahblah"}
echo ${name:="file.ext"}

1 Comment

Hmph, I don't know why I didn't realize that... I guess that solves my problem. Thanks!
0

It's simply

variable_name=value

If you use $(variable_name:=value} bash substitutes the variable_name if it is set otherwise it uses the default you specified.

1 Comment

That was the point. Sorry about not specifying that in the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.