I would like to test if the name of a variable given as argument to a function contains a certain string, and do different actions if it does/does not.
Here is a very basic description of what I want to achieve:
#!/bin/bash
varA="a"
varB="b"
varC="c"
varD="d"
varE="e"
varF="f"
function1 ()
{
if name of argument $1 does not contain "A"; then
echo "no A in $1"
further actions done using the value of varA and others...
elif name of argument $1 contains "A"; then
echo "A in $1"
further actions done using the value of varA and others...
fi
}
function1 $varA $varB $varC
function1 $varD $varE $varF
And when running this would give
A in varA
no A in varD
I saw while doing some research that the name of a variable could be referred to as ${!var@}, so here is the code I tried:
1 #!/bin/bash
2
3 varA="a"
4 varB="b"
5 varC="c"
6 varD="d"
7 varE="e"
8 varF="f"
9
10 function1 ()
11 {
12 if [[ "${!1@}" != *"A" ]]; then
13 echo "no A in $1"
14 elif [[ "${!1@}" == *"A" ]]; then
15 echo "A in $1"
16 fi
17 }
18
19 function1 $varA $varB $varC
20 function1 $varD $varE $varF
But when running the script it gives the following error messages:
./testx.sh: line 12: ${!1@}: bad substitution
./testx.sh: line 12: ${!1@}: bad substitution
Any help would be much appreciated! Thank you
function1 $varA $varB $varC(see my second code), and I am not using the values of the variables here, but in the real script I am working on, I want to use their values to perform other actions in the function.${!prefix@}"Expands to the names of variables whose names begin withprefix"; that is, it is the equivalent to the file globprefix*, but over the names of shell variables.prefixis just a string of characters.${!@}? Shouldn't this expand to the names of all arguments, something likevarA varB varCor$varA $varB $varC? Both would be good for what I want to do. When I try it it gives some empty lines as output.{!@}is not valid, but if it were valid it would be the list of all variables. An argument is just a string; arguments don't have names. (More precisely, they do have names:$1,$2, ...., but those are parameter names, not variable names. The expression which produced the argument is not its name.) The reason you can't do what you want to do is that the argument has already undergone parameter expansion by the time your function sees it, so it is just a string (which is the value of the variable).