Home > OS >  Pass in bash terminal variables to a bash script
Pass in bash terminal variables to a bash script

Time:02-08

If I am in a Linux terminal and I start setting variables such as export AGE=45.

then I have a script to read user data from terminal variables and process it, is this possible to do?

IE:

user@linux$ export AGE=45

user@linux$ ./age.sh

#script asks for input

read -p "what is your age?" scriptAGE

#user inputs variable set in terminal

$AGE

#echo output

echo "your age is: " $scriptAGE" 

#should say your age is: 45

CodePudding user response:

Variables are not expanded in input, only in the script itself.

You could use eval to force it to process the variable value as shell syntax.

eval "echo 'your age is:' $scriptAGE"

But this will also process other shell syntax. If they enter $AGE; rm * it will say their age is 45 and then delete all their files.

CodePudding user response:

you could just do

age=$1
echo "Your age is $1"

where $1, $2, $3, .., $N are the passed arguments by order

And then run your script

bash script sh Noureldin

For more Info read this:

CodePudding user response:

There is no such thing as a terminal variable. read just assigns a string to your variable scriptAGE.

If this string contains some $NAME you want to expand, you could apply eval to it, but this is of course extremely dangerous because of possible code injection.

A safer way to do this is using envsubst, but this requires that the variables to be substituted must be environment variables. In your case, AGE is in the environment, so this condition is met.

In your case, you would have to do therefore a

envsubst <<<"$scriptAGE"

which would print on stdout the content of scriptAGE with all environment variables in it substituted.

  •  Tags:  
  • Related