为什么我无法在此 bash 脚本中获取命令的退出值?

tes*_*act 9 shell exit

所以我正在编写这个小鹦鹉螺脚本,用于将视频转码为 mp3:

#! /bin/bash -x

if [ -z "$1" ]
    then
    zenity --warning --text="Error - No file selected !"
    exit 1
fi

BASEFILENAME=${1%.*}

exec ffmpeg -i "$1" -ab 256k "$BASEFILENAME.mp3" &&

if [ "$?" -eq 0 ]
    then
    zenity --info --text="Converting successful"
    exit
fi
Run Code Online (Sandbox Code Playgroud)

问题是,虽然 ffmpeg 命令执行成功了 if [ "$?" -eq 0 ]

似乎没有被触发。这是为什么?是&&错误还是其他原因?

gee*_*aur 13

可以达到该语句的唯一方法是exec它本身是否失败;如果成功,该ffmpeg命令将完全替换外壳。(迂回地,&&在这种情况下也将失败,因此根本无法访问exec它。)您不想要它,只需运行它。


Ric*_*rri 5

exec command语句用command. 也就是说,您的脚本实际上终止于第exec ffmpeg ...; 当且仅当ffmpeg在您的 PATH 中找不到该命令(或由于其他原因无法启动)时,才会执行剩余的行。

您可以exec通过help exec在 bash 命令提示符下键入来获取有关bash 内置的更多详细信息:

$ help exec
exec: exec [-cl] [-a name] [command [arguments ...]] [redirection ...]
    Replace the shell with the given command.

    Execute COMMAND, replacing this shell with the specified program.
    ARGUMENTS become the arguments to COMMAND.  If COMMAND is not specified,
    any redirections take effect in the current shell.
    [...]
Run Code Online (Sandbox Code Playgroud)