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
!var
that I've seen. – Tim Kennedy May 30 '19 at 16:24for arg in "$@"
boils down to merefor arg
. – jno May 31 '19 at 07:55