Override a variable in a Bash script from the command line
You need to use parameter expansion for the variable(s) you want to override:
$ cat override.sh
#!/bin/bash
: ${var1:=foo} # var1 will take on the value "foo" if not overridden
var2=${var2:-foo} # same thing but more typing
echo "var1 is $var1 | var2 is $var2"
Without Override Values
$ ./override.sh
var1 is foo | var2 is foo
With Override Values
$ var1=bar var2=baz ./override.sh
var1 is bar | var2 is baz
Bash isn't like Make or Ant. Those two programs won't allow you to reset the value of a macro/property once it is set on the command line. Instead in Bash, you'll have to write your scripts in such a way that allows you to set these values from the command line and not override them inside your scripts.
You might want to look at the getopts command which is a Bash builtin. That gives you an easy, flexible way to parse command line arguments and set values from the command line. For example, I have four variables OPT_A
, OPT_B
, OPT_C
, and OPT_D
. If I don't pass the parameter, they get their default value. However, I can override that default value on the command line:
USAGE="$0 [-a <a> -b <b> -c <c> -d <d>]"
OPT_A="Default Value of A"
OPT_B="Default Value of B"
OPT_C="Default Value of C"
OPT_D="Default Value of D"
while getopts ':a:b:c:d:' opt
do
case $opt in
a) OPT_A=$OPTARG;;
b) OPT_B=$OPTARG;;
c) OPT_C=$OPTARG;;
d) OPT_D=$OPTARG;;
\?) echo "ERROR: Invalid option: $USAGE"
exit 1;;
esac
done
You can also export your environment variables to allow your Bash scripts access to them. That way, you can set a variable and use that value.
In Bash, the ${parameter:=word}
construct says that if $parameter
is set, use the value of $parameter
. However, if $parameter
is null or unset, use word
instead.
Now, imagine if you did this:
$ export COMMANDLINE_FOO="FUBAR"
Now the variable $COMMANDLINE_FOO is set and readable for your shell scripts.
Then, in your shell script, you can do this:
FOO=BARFU
[...] #Somewhere later on in the program...
echo "I'm using '${COMMANDLINE_FOO:=$FOO}' as the value"
This will now print
I'm using 'FUBAR' as the value
instead of
I'm using 'BARFU' as the value
You should specify the variable with the following syntax:
MYVAR=74 ./myscript.sh
Within the script, check if it is already set before setting it:
if [ ! -z $MYVAR ]; then
#do something
fi