Home > OS >  How to get variables config from shell
How to get variables config from shell

Time:01-15

cat a.sh

#!/bin/bash
t=1232
echo $1
#echo $t

when i run the script "./a.sh $t" I can't get value 1232 when the script replacement with echo $t ,run the script "./a.sh" can get vaule 1232

can anybody else tell me ,if i use "./a.sh $t" this form ,how can get the vaule,thanks alot

have no ideas to get the variables throug the termi

CodePudding user response:

I think your variable t are out of scope. Therefore, what you want to do is assign the variable t=1232, beforehand, and use it as an argument. So the script would be

#!/bin/bash
echo $1

Then call the script as you wanted to with variable t already assigned to the value, so it would print the desired output

t=1232
./script.sh $t

I think that's that. would love to hear your thoughts tho

CodePudding user response:

When you run "./a.sh $t your current shell evaluates $t to '', so your script end up just echo ''.

If you quote the the variable either ./a.sh \$t or ./a.sh '$t' your script will do echo '$t'. You can then use either eval to get it to evaluate the expression:

eval echo $1

or preferable strip off the leading '$' and use indirect variable:

var=${1:1}
echo ${!var}

If you just need to store data use json or sqlite instead of a script.

If you have logic in your script consider just passing in the variable names and if not set dump all variables (using the name convention that your variables are lower case):

#!/bin/bash
if [ -z "$1" ]
then
    set | grep "^[a-z]"
    exit 0
fi
[ -z "$1" ] && 1=.*
for v in "$@"
do
    set | grep "^$v="
done

and you then do:

$ ./a t
t=1232
$ ./a
t=1232
  • Related