Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 如何根据“文件名”检查文件是否存在;模板";在目录里?_Bash_Variable Expansion - Fatal编程技术网

Bash 如何根据“文件名”检查文件是否存在;模板";在目录里?

Bash 如何根据“文件名”检查文件是否存在;模板";在目录里?,bash,variable-expansion,Bash,Variable Expansion,给定名为template的变量,例如:template=*.txt 如何检查当前目录中是否存在类似此模板的文件 例如,根据上面的模板的值,我想知道当前目录中是否有后缀为.txt的文件。使用查找: : > found.txt # Ensure the file is empty find . -prune -exec find -name "$template" \; > found.txt if [ -s found.txt ]; then echo "No matching

给定名为
template
的变量,例如:
template=*.txt

如何检查当前目录中是否存在类似此模板的文件

例如,根据上面的
模板的值,我想知道当前目录中是否有后缀为
.txt
的文件。

使用
查找

: > found.txt  # Ensure the file is empty
find . -prune -exec find -name "$template" \; > found.txt
if [ -s found.txt ]; then
  echo "No matching files"
else
  echo "Matching files found"
fi
严格地说,您不能假设
found.txt
每行只包含一个文件名;带有内嵌换行符的文件名看起来与两个单独的文件相同。但这确实保证了空文件意味着没有匹配的文件

如果需要匹配文件名的准确列表,则需要在保持路径名扩展的同时禁用字段拆分

[[ -v IFS ]] && OLD_IFS=$IFS
IFS=
shopt -s nullglob
files=( $template )
[[ -v OLD_IFS ]] && IFS=$OLD_IFS
printf "Found: %s\n" "${files[@]}"

这需要几个
bash
扩展(为了方便还原
IFS
,需要使用
nullglob
选项、数组和
-v
操作符)。数组中的每个元素正好是一个匹配项。

我会使用内置元素这样做:

templcheck () {
    for f in * .*; do
        [[ -f $f ]] && [[ $f = $1 ]] && return 0
    done
    return 1
}
这将模板作为参数(必须引用以防止过早扩展),如果当前目录中存在匹配项,则返回success。这适用于任何文件名,包括带有空格和换行符的文件名

用法如下所示:

$ ls
 file1.txt  'has space1.txt'   script.bash
$ templcheck '*.txt' && echo yes
yes
$ templcheck '*.md' && echo yes || echo no
no
要与变量中包含的模板一起使用,还必须引用该展开式:

templcheck "$template"

除了找到
之外,你还能找到更多的解决方法吗?我问它是因为我想知道如何从
模板
中获取模板并使用它。也就是说,如果给定参数来自
模板
,我如何检查用户提供的参数?(也就是说,如果
$1==${template}
,但肯定不是这样工作的)。@BenjaminW。细节,细节;)也许是这个<代码>查找-prune-exec find-name“$template”\对我有效,并且似乎是POSIX-only;做
say?还有
dotgob
选项,允许
*
匹配与
*
@AskMath相同的文件,如果模板中没有空格,它将使用
rm$template
(无引号)。如果可能有空格,您可以调整我的函数以执行
rm“$f”
,而不是
返回0
<使用
-exec rm{}
-delete
(如果您有GNU
find
)查找
可能更方便。@AskMath您不能引用
[[]]
右侧的
$template
。@AskMath您的模板是
.ord
,但它应该是
*.ord