显示错误并在cd错误退出时退出 [英] Display error and exit when cd exits with error
问题描述
当cd命令失败时,我想让我的脚本退出并显示一条消息.我尝试执行以下操作:
I want to let my script exit with a message when a cd command fails. I tried that by do the following:
cd $foo || echo "Error xyz"; exit 1
但是,无论cd成功与否,都将调用exit.当我键入以下内容时,它也不起作用,因为exit仅退出子shell:
However, exit gets called regardless of the cd's success. When I type the following, it does not work either, because exit only exits the subshell:
cd $foo || ( echo "Error xyz"; exit 1 )
如何在不定义功能的情况下实现所需的行为?当然,我只能将$(pwd)与$ foo进行比较,但这可能会导致符号链接和内容方面的问题.
How can I achieve the desired behaviour without defining a function? Of course I could just compare $(pwd) with $foo, but that could lead to problems regarding symlinks and stuff.
推荐答案
您可以使用 {列表;}
复合命令.命令列表在当前的shell上下文中执行:
You can use the { list; }
compound command. The list of commands is executed in the current shell context:
cd "$foo" || { echo "Error xyz"; exit 1; }
(请注意,结尾的分号或换行符是必需的.)
(Note the trailing semicolon or newline is required.)
bash
中最常见的功能定义通常正是将这种复合命令用于功能主体":
The most common definition of functions in bash
usually uses exactly this compound command for the "function body":
f() { list; }
尽管, bash
函数可以使用任何复合命令为其主体定义,例如:
although, bash
functions can be defined with any compound command for their body, for example:
f() ( list; )
f() (( $1 > 10 ))
f() [[ $1 != "test" ]]
偶:
f() for i in {1..10}; do echo $i; done
f() case ... esac
这篇关于显示错误并在cd错误退出时退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!