命令失败时继续执行脚本

我正在编写脚本以删除$ 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
评论
  • 克制
    克制 回复

    The problem is that $file expands only to Desktop, not all elements of the array. $file is equivalent to ${file[0]}.

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

    You aren't using set -e, so whether rm succeeds or fails as no effect on the rest of the loop or script.