所以我有一个充满命令的数组,我想运行每个元素并将其输出到屏幕,并检查每个命令中是否有错误并回显“ Command failed”。我看不到找到以编程方式执行此操作的方法,我基本上想运行命令,而命令的错误输出不会淹没整个屏幕。
示例:
array=(
"cat something"
"grep something"
"rm something"
"read -r -p 'something' something"
)
length=${#array[@]}
for (( i=1; i<${length}+1; i++ ));
do
if echo ${array[$i-1]} | sh 2>/dev/null; then
echo "command succeded"
else
echo "command failed"
fi
done
答案 0 :(得分:-1)
我想这就是您要寻找的东西
command_list="command1;command2"
#I tried it with command_list="ls;ls <sub-directory>"
while IFS=';' read -ra command_array; do
for i in "${command_array[@]}"; do
# process "$i"
if ( $i &>/dev/null )
then
echo "Success"
else
echo "Failed"
fi
done
done <<< $command_list
如果您想知道为什么使用while循环,请阅读:https://stackoverflow.com/a/918931/11571342
编辑:如评论中所述,无法预先知道bash中命令的exit_status
。您将必须执行命令进行检查。但是有一种方法可以工作(但是使用rm
或insatll
时通常会失败)
while IFS=';' read -ra command_array; do
for i in "${command_array[@]}"; do
# process "$i"
$i &>/dev/null
exit_status=$?
if (( exit_status == 0 ))
then
$i
echo "Success...."
else
echo "Failed"
fi
done
done <<< $command_list