0

如果用户不是 root 并且我希望退出代码为 5,我希望我的脚本返回到 shell

who=`whoami`
if [ echo $who != "root"];
        then exit (5)
else

我究竟做错了什么?

4

3 回答 3

2

尝试这个:

who=`whoami`
if [ $who != "root" ]; then 
    exit 5
else
于 2013-06-23T12:03:47.387 回答
1

您还可以使用$(...)which 将在子 shell 中运行命令,从而无需额外的变量来存储有效的 uid。

if [ $(whoami) != "root" ]; then
  exit 5;
else
  ...
fi

或者,您可以使用id来获取相同的信息:

if [ $(id -un) != "root" ]; then
  exit 5;
else
  ...
fi
于 2013-06-23T12:50:23.263 回答
0

vinoqadhikary's answer is correct. gniourf_gniourf's comment also corrected a problem in the answer given.

why your code had problems:

The [ is actually an external command on my system: /usr/bin/[ Since it is a command, it wants to have white space around it so the shell can parse it for you.

type [

will show you what you have on your system.

When you put something inside parenthesis like this: ( stuff in here ) two things to note:

stuff in here 

will be executed as a command. 5 is not a command.

Next: if what you had for stuff in here was a real command the shell understood, then the shell would have run it as a child process -- not what you intended.

于 2013-06-23T12:39:04.190 回答