问题描述
我的bash脚本类似于:
I have bash script similar to:
{
# Try block
command 1
command 2
command 3
} || {
# Catch errors
while true; do
{
# Try block inside
# Change parameters for command 1, command 2
command 1
command 2
command 3
break
} || {
# Change parameters and try again
continue
}
done
}
此代码或多或少可以正常工作,但是...
More or less this code works fine, but...
出于某些原因尝试
部分的工作对我而言不是预期的。我以为如果我的某些命令未返回 0
代码会失败,但这不是真的。
For some reason try
sections works not as expected for me. I thought that it fails if some of my commands return not 0
code, but it's not true.
对于某些命令特定情况下,我的命令2
在第一个try块中返回 1
代码,但它不会失败,并进入 catch
部分, command 3
从此 try
块执行,即
For some specific cases my command 2
returns 1
code in the first try block, but it doesn't fail and goes into catch
section, command 3
executes from this try
block and that's it.
这是我的问题:
如何处理bash中的错误?只是为了玩返回码?
How to handle errors in bash? Just to play with return codes?
更新:
原始代码看起来非常类似于:
主要思想是所有3个命令应一个接一个地执行,并且它们都以某种方式与 folder_name
相关。
Original code looks very similar to:The main idea is that all 3 commands should be executed one-by-one and all of them are somehow related to folder_name
.
folder_name=my_folder
suffix=0
{
cd /home/test/
mkdir $folder_name
ls -la $folder_name
} || {
while true; do
suffix=$(expr $suffix + 1)
{
folder_name=$folder_name_$suffix
cd /home/test/
mkdir $folder_name
ls -la $folder_name
break
} || {
continue
}
done
}
推荐答案
我在这里看到两个问题。
I see two problems here.
使用花括号对命令进行分组时,必须在末尾(或右大括号前的换行符)。请参考
When grouping commands using curly braces, there must be a semicolon at the end (or a newline before the closing brace). Refer to docs here
另一方面,无论如何您都不考虑返回码。通常,您使用 [[$? -eq 0]]
。但是在这里,您可以简单地用&&
链接命令。
例如
On the other hand, you are not considering return codes anyway. You normally check the return code with something like [[ $? -eq 0 ]]
. But in here, you can simply chain the commands with &&
.e.g.
{
cd /home/test/ &&
mkdir $folder_name &&
ls -la $folder_name;
}
但是,以下操作将满足您的需求。
However, following will do what you need.
cd /home/test/
prefix=my_folder
suffix=0
folder_name="$prefix"
while true; do
if [[ -e $folder_name ]]; then
folder_name="${prefix}_$((++suffix))"
continue
fi
mkdir "$folder_name"
if [[ $? -ne 0 ]]; then
echo "mkdir failed"
exit 1
fi
break
done
这篇关于重击:正确处理错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!