首页 > 解决方案 > 如果没有文件与 glob 匹配,则防止“mv”命令引发错误。例如" mv *.json /dir/

问题描述

我想将 jenkins 作业中创建的所有 JSON 文件移动到不同的文件夹。

作业可能不会创建任何 json 文件。在这种情况下, mv 命令会引发错误,因此该作业会失败。

如果找不到文件,如何防止 mv 命令引发错误?

标签: bashshellmv

解决方案


这是预期的行为——这就是为什么*.json在没有匹配项时shell未展开的原因,以允许mv显示有用的错误。

但是,如果您不希望这样,您始终可以自己检查文件列表,然后再将其传递给mv. 作为一种适用于所有符合 POSIX 的 shell 的方法,而不仅仅是 bash:

#!/bin/sh

# using a function here gives us our own private argument list.
# that's useful because minimal POSIX sh doesn't provide arrays.
move_if_any() {
  dest=$1; shift  # shift makes the old $2 be $1, the old $3 be $2, etc.
  # so, we then check how many arguments were left after the shift;
  # if it's only one, we need to also check whether it refers to a filesystem
  # object that actually exists.
  if [ "$#" -gt 1 ] || [ -e "$1" ] || [ -L "$1" ]; then
    mv -- "$@" "$dest"
  fi
}

# put destination_directory/ in $1 where it'll be shifted off
# $2 will be either nonexistent (if we were really running in bash with nullglob set)
# ...or the name of a legitimate file or symlink, or the string '*.json'
move_if_any destination_directory/ *.json

...或者,作为一种更特定于 bash 的方法:

#!/bin/bash

files=( *.json )
if (( ${#files[@]} > 1 )) || [[ -e ${files[0]} || -L ${files[0]} ]]; then
  mv -- "${files[@]}" destination/
fi

推荐阅读