使命令失败时继续执行脚本

时间:2020-04-24 12:04:17

标签: arrays bash syntax

我正在编写脚本以删除$ HOME中不需要的文件。

如果for循环中的命令返回错误,我需要脚本继续。 我试图遵循另一个Stack Overflow线程的建议,该线程说使用这种格式:

command || true

但是,这似乎不适用于我在for循环内执行代码的情况。该脚本退出循环,并在循环后继续执行各行。

脚本:

#!/usr/bin/env bash

files=(
  "Desktop"
  ".yarnrc"
)

cd $HOME
for file in $files;
do
  echo "current file: $file"
  rm -r "$file" || :
done

echo "hello world"

输出:

current file: Desktop
rm: cannot remove 'Desktop': No such file or directory
hello world

1 个答案:

答案 0 :(得分:3)

问题在于$file仅扩展 Desktop,而不是数组的所有元素。 $file等同于${file[0]}

cd
for file in "${files[@]}"; do
  echo "current file: $file"
  rm -r -- "$file"
done

您没有使用set -e,因此rm成功或失败对循环或脚本的其余部分没有影响。