如何解决测试具有扩展名的现有文件失败并使用通配符
只是一个简单的终端会话:
$ # the file really exists
$ [[ -e mydir/564df455-92e6-ac59-9b96-b3665f2aa3c7.vmem ]]
$ echo $?
0
$ # not with globbing though
$ [[ -e mydir/*.vmem ]]
$ echo $?
1
我错过了什么?
更新
compgen
按预期工作:
$ compgen -G "mydir/*.vmem"; echo $?
0
但是,我想知道为什么最初的尝试不起作用。我想学习 Bash,而不仅仅是让它工作并继续学习。我检查过:noglob
未设置。
更新 2
根据@Aaron,这应该(并且确实)适用于原始测试:
$ files=( mydir/*.vem )
$ [[ ${#files[@]} -gt 0 ]]; echo $?
0
这个版本实际上更容易在我的脚本函数中编写和理解(问题出现的地方)。整个脚本用于将 vmware 同步到时间机器卷上的备份文件夹。
使用 compgen
:
# get the status of a vm
# argument: path to the vm
# compgen exit code: 0 - path(s) found,1 - nothing found
function vm_status() {
local vm_path="$1"
local status=-1
[[ $status -lt 0 ]] && { compgen -G "$vm_path/*.vmem" > /dev/null; } || { status=0; } # vm is shut down: vm does not contain file with extension .vmem
[[ $status -lt 0 ]] && { compgen -G "$vm_path/*.vmss" > /dev/null; } && { status=1; } # vm is suspended: vm contains file with extension .vmss
[[ $status -lt 0 ]] && { compgen -G "$vm_path/*.vmem.lck" > /dev/null; } && { status=2; } # vm is running: vm contains folder name ending with .vmem.lck
echo $status # should return 0,1 or 2
}
compgen
不需要丢弃 [[
输出:
# get the status of a vm
# argument: path to the vm
function vm_status() {
shopt -s nullglob # prevents non-matching glob from reporting one file (the glob itself)
local vm_path="$1"
local status=-1
[[ $status -lt 0 ]] && { files=( "$vm_path"/*.vmem ); } && [[ ${#files[@]} -gt 0 ]] || { status=0; } # vm is shut down: vm does not contain file with extension .vmem
[[ $status -lt 0 ]] && { files=( "$vm_path"/*.vmss ); } && [[ ${#files[@]} -gt 0 ]] && { status=1; } # vm is suspended: vm contains file with extension .vmss
[[ $status -lt 0 ]] && { files=( "$vm_path"/*.vmem.lck ); } && [[ ${#files[@]} -gt 0 ]] && { status=2; } # vm is running: vm contains folder name ending with .vmem.lck
echo $status # should return 0,1 or 2
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。