Ubuntu – How to program a shell script to start another script and use the same variable values

bashscripts

I'm not giving the real example as the post becomes so long that no one would read it. So I'll give other examples
I have a bash script name.sh and it is programmed as below-

#!/bin/bash
echo "Please Enter your name"
read name
echo "Hello $name"
sudo bash age.sh

And another script(say age.sh) like this-

#!/bin/bash
*echo "Hello $name"
echo "Please enter your age"
read age
echo "Thank you"

*Here in the second script I want the variable $name from the first script to be used with the same value in the second script so the user doesn't have to type his name again
Of course if I'm declaring a variable then I can do it in the other script too but if the user is declaring it then I can't predict what the user will answer. So how do I transfer the same value over to the other script?
I have another idea to do it
It goes like this-

#!/bin/bash
echo "Please Enter your name"
read name
echo "Hello $name"
sudo bash age.sh --variable_value

Somehow can i make the 2nd script use the values given after — and assign the same variables to them?

Best Answer

Export the variable in the calling script:

read name
export name="$name"

This way, the variable will propagate to any called script and sub-shells.

To retrieve command line parameters in a script, use the variables "$1", "$2", ... These are populated with the different arguments you passed to the command. "$0" will retrieve the name of the command itself, "$@" will retrieve the entire parameter string at once.

Related Question