2

是否可以从使用命令替换调用的函数中退出脚本?

例如

#/bin/bash
function do_and_check()
{
    ls $1 || exit
}

p=$(do_and_check /etc/passwd)
q=$(do_and_check /xxx)

运行结果是

bash -x yyy                                                                                                             
++ do_and_check /etc/passwd                                                                                                                  
++ ls /etc/passwd                                                                                                                             
+ p=/etc/passwd
++ do_and_check /xxx
++ ls /xxx
ls: cannot access /xxx: No such file or directory
++ exit
+ q=
+ echo /etc/passwd
/etc/passwd

我本来希望退出让我脱离脚本,而不是脱离命令替换。那可能吗?

4

1 回答 1

3

这个:

p=$(do_and_check /etc/passwd)

正在执行一个子shell,这就是您要退出的内容。我会在您的函数中设置退出值(设置为非零值),然后$?在命令替换后检查返回值。

于 2013-01-03T09:42:38.013 回答