开发者

Bash scripts handled differently then typing in the terminal?

I'm开发者_运维问答 having some problems with bash scripting. I want the script to find the "Firefox.app" directory, but things that work when I type them in the shell interpreter don't work in the script.

ffxapp=`find /Applications/ -name "Firefox.app" -print | tee firefox.location`

When I type that into the shell, it works ($ffxapp == "/Applications/Firefox.app"). In a script, it doesn't ($ffxapp == ""). I am so confused.


Let me turn my telepathic mode on. The most probable cause of your problem is that you are assigning a variable in the script and expect it to appear in your shell when you are checking for it. However, when script is ran by a shell, it creates a sub-shell so all variables declared there are not exposed to the environment of a parent shell. If you want to export a variable from the script, you have to explicitly tell the bash to run it in the same shell. OK, too much words, here is an example:

#!/bin/bash

FOO=bar

When you run this script, FOO variable will not appear in your shell even if you use "export":

$ cat test.sh 
#!/bin/bash

FOO=bar

$ ./test.sh 
$ echo $FOO

$ 

But if you run it using "source" command, it will work:

$ source ./test.sh 
$ echo $FOO
bar
$ 

Hope it helps :)


Adding to Vlad's answer, by adding an echo $FOO in the script you can see the value is there when the script is running, but gone when the script has terminated:

$ cat test.sh
#!/bin/bash

FOO=bar
echo $FOO

$ ./test.sh
bar
$ echo $FOO

$
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜