1

当我在 bash shell 中运行“set”命令时,我看到一个变量有一个值。但是,当我在 bash 脚本中运行“set”命令时,该变量不存在。为什么?我怎样才能做到这一点?

AxOS(7iq1) root:/mnt/ax/scratch/roshi# set
--snip--
SERIAL_NUMBER=7iq1
--snip--
AxOS(7iq1) root:/mnt/ax/scratch/roshi# 

我的 shell 脚本 tmp.sh 包含

#!/bin/bash
svcid=`set | grep ^SERIAL_NUMBER | awk '{ split($1,a,"=");print a[2] }'`
echo ${svcid}

如果我按如下方式执行脚本,则没有输出

AxOS(7iq1) root:/mnt/ax/scratch/roshi# ./tmp.sh

AxOS(7iq1) root:/mnt/ax/scratch/roshi# 

如果我执行脚本(首先由 Doon 建议)

AxOS(7iq1) root:/mnt/ax/scratch/roshi# . ./tmp.sh
7iq1
AxOS(7iq1) root:/mnt/ax/scratch/roshi# 
4

2 回答 2

3

一些(但不一定是全部)shell 变量被标记为导出到环境中。只有这些变量在子进程(如 shell 脚本)中可见。例如:

$ x=3         # shell variable
$ export y=5  # shell variable exported to the environment
$ cat example.sh
echo "value of x: $x"
echo "value of y: $y"
$ bash example.sh
example of x:
example of y: 5
于 2013-04-26T18:38:26.637 回答
0

这是因为 shell 脚本在与调用者不同的环境中运行在一个单独的进程中。你想用env VAR=[value] [script-command]来解决这个问题。你问了一个例子,你去:

% bash # I use zsh and this is a paste from the terminal
$ echo "echo $VAR" > /tmp/echo.sh
$ sh /tmp/echo.sh

$ env VAR='hello' sh /tmp/echo.sh
hello
$
于 2013-04-26T18:31:43.467 回答