In the case of bash
, that depends on whether $SHELLOPTS
is in the environment or not.
bash-4.4$ export SHELLOPTS
bash-4.4$ set -x
bash-4.4$ bash -c 'echo x'
+ bash -c 'echo x'
+ echo x
x
See how the bash -c 'echo x'
inherited the xtrace
option. For the options set by shopt
, it's the same but with the $BASHOPTS
variable.
It comes handy especially for the xtrace
option for debugging when you want to run a bash
script (or any command running a bash
script) and all other bash
script it may invoke, recursively with xtrace
(provided nothing does a set +x
in those scripts). If your sh
is bash
, that will also affect them, so also the system("command line")
made in other languages:
env SHELLOPTS=xtrace some-command
One way to accomplish this is through indirection -- referring to another variable from the value of the first variable.
To demonstrate:
apple="Red"
var="apple"
echo "${!var}"
Results in:
Red
Because bash first takes !var
to mean the value of the var
variable, which is then interpreted via ${apple}
and turned into Red
.
As a result, your GetFruitColour.sh script could look like:
#!/bin/bash
source ./fruitcolour.sh
for arg in "$@"
do
printf 'The colour of %s is %s.\n' "$arg" "${!arg}"
done
I've made the path to the sourced script relative instead of bare, to make it clearer where the file is (if the given filename does not contain a slash, shells will search the $PATH
variable for it, which may surprise you).
I've also changed echo
to printf
.
The functional change is to use the looping variable $arg
and the indirect expansion of it to produce the desired values:
$ ./GetFruitColour.sh apple mango
The colour of apple is Red.
The colour of mango is Yellow.
Do note that there's no error-checking here:
$ ./GetFruitColour.sh foo
The colour of foo is .
You may find it easier to use an associative array:
declare -A fruits='([orange]="Orange" [apple]="Red" [mango]="Yellow" [pear]="Green" )'
for arg in "$@"
do
if [ "${fruits["$arg"]-unset}" = "unset" ]
then
echo "I do not know the color of $arg"
else
printf 'The colour of %s is %s.\n' "$arg" "${fruits["$arg"]}"
fi
done
Best Answer
No, what you are doing is a coding pattern called "guard clauses" which is a good thing to do. Handling these trivial error cases later in the code may make it more complicated than necessary.