bash - 如果没有文件与 glob 匹配,则防止“mv”命令引发错误。例如" mv *.json /dir/
问题描述
我想将 jenkins 作业中创建的所有 JSON 文件移动到不同的文件夹。
作业可能不会创建任何 json 文件。在这种情况下, mv 命令会引发错误,因此该作业会失败。
如果找不到文件,如何防止 mv 命令引发错误?
解决方案
这是预期的行为——这就是为什么*.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
推荐阅读
- python - 我在使用 python-bs4 抓取请求时不断收到不同的错误消息
- sql - 在 SQL 中计算转化率
- typescript - TypeScript:接口取决于(递归)属性的类型
- sql - Postgresql group by 显示所有元素甚至为空
- angular - 如何允许用户在另一个选项卡中打开页面而不必再次登录
- xcode - Xcode 12 更新中断 Pod 和产品
- c# - Log all handles exception
- css - 有条件地将文本列表分成两列
- sql - 使用 MAX 查找给定其他属性的最新时间
- postgresql - Azure Postgres PaaS - 如何将 IP 地址列入白名单?