简体   繁体   中英

How to get set variable in a shell script

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM