0

I can succeed to grab the environment variable in command line.

But if I put the commands in a .sh file, then run the .sh file.

Nothing is printed. Any reason ?

root@mydesktop:/tmp$ s1="hello stackoverflow"
root@mydesktop:/tmp$ echo $s1
hello stackoverflow
root@mydesktop:/tmp$/tmp$ set | grep s1
s1='hello stackoverflow'

--> it's good to show as expect, then I save those commands to a script file test.sh

#!/bin/sh    
echo $s1
echo ${s1}    
hello=$( set | grep s1 )
echo $hello   
echo ${hello}

But after script run, I don't get the expected result

root@mydesktop:/tmp$ ./test.sh


root@mydesktop:/tmp$ 

Any idea ?

Update:

OK , found strange thing:

#set
s1=' balaba '
'
s2='another string'

the is one more ' --> it could be the root cause.

5
  • I suggest you to quote the variables. Commented Apr 27, 2017 at 7:44
  • quote the variables doesn't help. Commented Apr 27, 2017 at 7:52
  • For me it works in bash (though your code, in general, would show much more than just the setting of the variable). What bash version do you have, i.e. what does echo $BASH_VERSION say? Commented Apr 27, 2017 at 7:55
  • If you want to export a variable, you need to export it! :) export s1="foo bar" Commented Apr 27, 2017 at 7:55
  • s1 is example here. It's not set by me. It's there after system boot up. Commented Apr 27, 2017 at 7:58

1 Answer 1

2

By default variables declared without export are not passed to subprocesses.

 export s1="hello stackoverflow"

if it was set not by you , just export it:

export s1

./test.sh

---output

hello stackoverflow
s1='hello stackoverflow'

And of course use quotes:

#!/bin/sh
echo "$s1"
hello=$( set | grep s1 )
echo "$hello
Sign up to request clarification or add additional context in comments.

2 Comments

But in my real product environment, I still can't get the value. let me check what's the different.Will feedback later.
export should be before script run, not inside. Before running test.sh

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.