0

I have 2 scripts:

  1. script: script1.sh

    #!/bin/bash
    [[ $0 = "$BASH_SOURCE" ]] && { echo "You must source me!"; exit; }
    if [ -z ${I} ]; then
         echo
         echo -n "some string: "
         stty -echo
         read I
         #export I
         stty echo
         echo
    else
         echo "ALREADY SET!!!"
    fi
    echo "--- $I"
    
  2. script: script2.sh

    #!/bin/bash
    echo "--- $I"
    if [ -z $I ]; then
            echo "VARIABLE NOT SET"
    else
            echo "VARIABLE SET"
    fi
    

And now the part that confused me... I first run script1 and then script2...

First scenario:

As you can see I can print $I variable (value: asd) inside script1. When I run script2 it returns "VARIABLE NOT SET", but when I try to echo $I I get "asd"

wolfy@VMtest:~$ . ./script1.sh

some string:
--- asd
wolfy@VMtest:~$ ./script2.sh
---
VARIABLE NOT SET
wolfy@VMtest:~$ echo $I
asd
wolfy@VMtest:~$

Second scenario:

Now I uncomment #export I and rerun both scripts as before (before rerun I created a new session so that all variables are reseted)

In this case I can read $I in script2 and echo it

wolfy@VMtest:~$ . ./script1.sh

some string:
--- asd
wolfy@VMtest:~$ ./script2.sh
--- asd
VARIABLE SET
wolfy@VMtest:~$ echo $I
asd

Can someone explain me why in my first scenario I can echo $I, but I can't use it in second script?

1 Answer 1

2

Because you didn't export it. Exporting a variable moves it from the current shell's variable list into the environment. Subprocesses only read existing variables from the environment.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for your explanation... but why can I echo it from prompt?
Because the "prompt" is the current shell.
Absurdly minor nit. It turns out 'export' does not necessarily move the variable into the environment. In bash it does, but in general it merely ensures that the variable will be in the environment of all subprocesses. Why any shell would choose to implement this behavior in any other way than simply putting the variable in the environment is baffling, but dash at least chooses not to do so. (Or did at the last version I checked, which was a few years ago.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.