简体   繁体   English

即使在退出命令后,Shell脚本仍继续运行

[英]Shell script continues to run even after exit command

My shell script is as shown below: 我的shell脚本如下所示:

#!/bin/bash

# Make sure only root can run our script
[ $EUID -ne 0 ] && (echo "This script must be run as root" 1>&2) || (exit 1)

# other script continues here...

When I run above script with non-root user, it prints message "This script..." but it doe not exit there, it continues with the remaining script. 当我使用非root用户运行上面的脚本时,它会输出消息“This script ...”但它不会从那里退出,它继续使用剩余的脚本。 What am I doing wrong? 我究竟做错了什么?

Note: I don't want to use if condition. 注意:我不想使用if条件。

You're running echo and exit in subshells. 你正在运行echoexit子shell。 The exit call will only leave that subshell, which is a bit pointless. 退出调用只会留下子shell,这有点无意义。

Try with: 试试:

#! /bin/sh
if [ $EUID -ne 0 ] ; then
    echo "This script must be run as root" 1>&2
    exit 1
fi
echo hello

If for some reason you don't want an if condition, just use: 如果由于某种原因你不想要if条件,只需使用:

#! /bin/sh
[ $EUID -ne 0 ] && echo "This script must be run as root" 1>&2 && exit 1
echo hello

Note: no () and fixed boolean condition. 注意:no ()和固定的布尔条件。 Warning: if echo fails, that test will also fail to exit. 警告:如果echo失败,该测试也将无法退出。 The if version is safer (and more readable, easier to maintain IMO). if版本更安全(更易读,更易于维护IMO)。

I think you need && rather than || 我认为你需要&&而不是|| , since you want to echo and exit (not echo or exit). ,因为你想回声退出(不回声退出)。

In addition (exit 1) will run a sub-shell that exits rather than exiting your current shell. 另外(exit 1)将运行一个退出而不是退出当前shell的子shell。

The following script shows what you need: 以下脚本显示了您的需求:

#!/bin/bash
[ $1 -ne 0 ] && (echo "This script must be run as root." 1>&2) && exit 1
echo Continuing...

Running this with ./myscript 0 gives you: 使用./myscript 0运行此./myscript 0可以:

Continuing...

while ./myscript 1 gives you: ./myscript 1给你:

This script must be run as root.

I believe that's what you were looking for. 我相信这就是你要找的东西。

I would write that as: 我会把它写成:

(( $EUID != 0 )) && { echo "This script must be run as root" 1>&2; exit 1; }

Using { } for grouping, which executes in the current shell. 使用{ }进行分组,在当前shell中执行。 Note that the spaces around the braces and the ending semi-colon are required. 请注意,大括号周围的空格和结束的分号是必需的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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