How do you override a variable in your Bash script from the command line?
I know how to pass variables in, but I just want something like ./myscript.sh -Dvar=v
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 -b -c -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