Shell脚本的第一行空白:解释UID变量的行为 [英] Blank first line of shell script: explain behavior of UID variable
问题描述
我有两个非常简单的脚本,不同之处仅在于第一行空白:
I have two very simple scripts, differing only by the presence of a blank first line:
$ cat test.bash
#!/bin/bash
echo ${UID}
$ cat test_blank.bash
#!/bin/bash
echo ${UID}
现在,无论是否包含nice
,我现在都可以运行:
Now I run then, with and without nice
:
$ ./test.bash
1060
$ ./test_blank.bash
1060
$ nice ./test.bash
1060
$ nice ./test_blank.bash
请说明为什么在最后的情况下未设置UID
变量的原因.将nice
替换为sudo
或nohup
时,行为是相同的.
Please explain why, in the final case, the UID
variable is unset. The behavior is the same when replacing nice
with sudo
or nohup
.
推荐答案
观察:
$ bash test_blank.bash
1060
$ dash test_blank.bash
bash
产生输出,但dash
(在类似debian的系统上是默认的sh
)不会输出.这是因为bash
设置了UID
,而破折号没有设置. ( POSIX 不需要shell来设置UID
.)因此,问题就变成了哪个shell执行脚本.
bash
produces output but dash
, which is the default sh
on debian-like systems, does not. This is because bash
sets UID
but dash does not. (POSIX does not require a shell to set UID
.) So, the question becomes which shell executes the script.
当bash看到./test.sh
时,它(bash)运行脚本.当另一个命令(例如nice
)接收脚本作为参数并且该脚本的第一行没有有效的shebang时,将运行默认的shell(可能为dash
).
When bash sees ./test.sh
, it (bash) runs the script. When another command, such as nice
, receives the script as an argument and the script does not have a valid shebang as the first line, then the default shell, likely dash
, is run.
如果要使用破折号的UID或任何其他不提供UID的外壳,请使用id
命令:
If you want UID in dash, or any other shell that does not provide it, use the id
command:
UID=$(id -u)
找出哪个外壳程序正在运行脚本
要查看哪个外壳程序正在运行脚本,请使用:
Finding out which shell is running a script
To see which shell is running a script, use:
$ cat test2.sh
#!/bin/bash
ps $$
echo UID=${UID}
在bash
下:
$ ./test2.sh
PID TTY STAT TIME COMMAND
1652 pts/12 S+ 0:00 bash -rcfile .bashrc
UID=1060
相比之下,如果使用nice
调用它,则可以看到它在/bin/sh
下运行,并且未分配UID变量:
If we invoke it using nice
, by contrast, we can see that it is running under /bin/sh
and the UID variable is not assigned:
$ nice test2.sh
PID TTY STAT TIME COMMAND
1659 pts/12 SN+ 0:00 /bin/sh test2.sh
UID=
这篇关于Shell脚本的第一行空白:解释UID变量的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!