Shell 使用 && 或 || 输出错误的脚本

Shell script with error output using && or ||

我正在编写一个 bash 代码,我希望用户在其中使用 zenity select 一个文件夹。问题是,如果文件夹名称中有一些空格,selection 将失败,但脚本将继续(我不想要的)。 这就是为什么我尝试在退出脚本之前告诉用户出现问题的原因。

inputStr=$(zenity --file-selection --directory "${HOME}")
cd $inputStr || zenity --error --width=300 --height=100 --text "The folder name must not contain spaces." && exit

当 selection 失败时,它会起作用。但事实是,当 selection 正常时,它也会退出脚本。我尝试用 «||» 替换 «&&»因为我以为我误解了什么,但是不管 selection 是否失败,它都会运行代码。

有人有想法吗?

在 shell 中,||&& 具有 相等的 优先级,并且在单个列表中从左到右计算。您期望它被解析并计算为 cd $inputstr || (zenity ... && exit),但它实际上被计算为 (cd $inputstr || zenity ...) && exit。因此,只要 cdzenity 成功,您的脚本就会退出,而不是调用 zenity 并在 cd 失败时退出.

即使 zenity 出于任何原因失败,您也可能想退出:使用 ;,而不是 &&

切勿在同一个列表中混用 &&||。相反,请使用正确的 if 语句。

if ! cd "$inputstr"; then
    zenity ...
    exit
fi