我是Bash脚本的新手,尽管多次尝试重构伪代码中显示的逻辑结构,但我无法使其工作。如何将if / else逻辑与for循环一起分割?
伪代码: 我有一个命令检查HDFS文件系统的目录中是否存在任何子文件夹。让我们调用这个命令_A。
If subfolders do NOT exist {
proceed with remaining execution of script
}
Else {
sleep for 30 minutes and run command_A again to see if the subfolders have been removed. Note: This sleep and re-check cycle should repeat up to 4 times and if subfolders are never removed the script is killed with exit 1
}
我试过的样本如下。我无法弄清楚我应该如何使用||与else语句一起使用。
使用这些结构:
1. for i in {1..4}; do command_A && break || sleep 1800; done
2. if command_A ; then echo "Command succeeded" else echo "Command failed" fi
测试示例:
for i in {1..4};
do
if hdfs dfs -test -e $mypath/*
echo "Folder is empty" && break
else
???
更新显示工作解决方案 :
for i in {1..4};
do
if hdfs dfs -test -e $mypath/*;
then
if [ $i -eq 4 ]
then
echo "script exiting now with code 1"
else
echo "Folder is full"
sleep 10
fi
else
echo "Folder is empty"
break
fi
done
答案 0 :(得分:1)
<强>更新强>
这是针对此特定问题的完整代码,我将保留原始稍微更通用的代码以供将来参考,因为对于搜索类似问题的其他人来说,它不那么复杂(如果/ else则嵌套少)。
for i in {1..4};
do
if hdfs dfs -test -e $mypath/*;
then
if [ $i -eq 4 ]
then
echo "script exiting now with code 1"
else
echo "Folder is full"
sleep 10
fi
else
echo "Folder is empty"
break
fi
done
我认为这样的事情会起作用,这就是你所拥有的。您只需将您要检查的内容放在if语句中,此代码应该适合您。
for i in {1..4}
do
if [ <check for subdirs> ]
then
echo "Folder is empty!"
break
else
sleep 1800
fi
done
答案 1 :(得分:0)
这会有用吗?
sleep_count=0
max_attempts=4
for ((i=0; i < $max_attempts; i++)); do
if hdfs dfs -test -e $mypath/*; then
echo "No subfolders!"
break
else
# subfolders exist; wait for a while and see if they go away
((sleep_count++))
sleep 1800
fi
done
if [[ $sleep_count == $max_attempts ]]; then
# waited too long for subfolders to go away
exit 1
fi
# probably repeat the above steps again?