ARYA1992
ARYA1992

Reputation: 141

How to use user entered variable value from one shell script to another shell script in linux?

I have a three shell script.Where I have to use user entered value count from script1.sh to script2.sh. How can I use user entered value count from script1.sh to script2.sh trhough main.sh?

scrip1.sh

read -p 'Enter a number:' count

script2.sh

echo "Count:$count"

main.sh

sleep 1 && ./script1.sh
sleep 1 && ./script2.sh

Upvotes: 0

Views: 61

Answers (1)

kvantour
kvantour

Reputation: 26471

How can I modify a global variable in a sub-shell?

This is your actual real question.

In short, you can't! (see here)

You want to have your variable $count be known to main.sh and modified by the sub-shell which executes script1.sh and passed to the sub-shell script2.sh for reading.

Passing a variable from the parent (main.sh) to a child for reading is possible when using EXPORT or declaring the variable as global. Eg.

#!/usr/bin/env bash
# This is main.sh
export count=5
./script2.sh

#!/usr/bin/env bash
# This is script2.sh
echo "$count"

This runs as:

$./main.sh
5

Modifying the variable is not possible:

#!/usr/bin/env bash
# This is main.sh
export count=5
./script1.sh
./script2.sh

#!/usr/bin/env bash
# This is script1.sh
count=7

This runs as:

$./main.sh
5

What Can you do?

If you want to modify a variable in parent, you have to ask script1.sh to return the value via /dev/stdout and then catch it.

And then you have two options:

  • declare count a global variable

    #!/usr/bin/env bash
    # This is main.sh
    export count=5
    count=$(./script1.sh)
    ./script2.sh
    
  • pass count as and argument

    #!/usr/bin/env bash
    # This is main.sh
    count=$(./script1.sh)
    ./script2.sh "$count"
    
    #!/usr/bin/env bash
    # This is my script2.sh
    count="$1"
    echo "$count"
    

This runs as:

$./main.sh
7

An alternative solution is to make use of source:

#!/usr/bin/env bash
# This is my main.sh
source ./script1.sh
source ./script2.sh

When you execute the script you are opening a new shell, type the commands in the new shell, copy the output back to your current shell, then close the new shell. Any changes to the environment will take effect only in the new shell and will be lost once the new shell is closed.

When you source the script you are typing the commands in your current shell. Any changes to the environment will take effect and stay in your current shell.

source: super user: What is the difference between executing a bash script vs sourcing it

Upvotes: 1

Related Questions