Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: "command not found" on simple variable assignment

Tags:

bash

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.

like image 355
beatgammit Avatar asked Jan 20 '23 01:01

beatgammit


1 Answers

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"
like image 195
Michał Šrajer Avatar answered Jan 21 '23 15:01

Michał Šrajer