我是 shell 脚本的新手,我有这个脚本:
#!/bin/bash
path_file_conf=/fullpath/directory/*.conf
if [ -e "$path_file_conf" ];then
echo "Found file"
else
echo "No found file"
fi
即使我在 /fullpath/directory/ 文件夹中有一个 .conf 文件,结果总是“找不到文件”。
我可以知道代码的哪一部分是错误的吗?提前致谢!
表达方式:
path_file_conf=/fullpath/directory/*.conf
可能有多个匹配的路径名。因此, 的值$path_file_conf最终可能是,例如:
/fullpath/directory/foo1.conf /fullpath/directory/foo2.conf
有条件的:
if [ -e "$path_file_conf" ]; then
检查单个文件是否存在。如果“/fullpath/directory/foo1.conf /fullpath/directory/foo2.conf”没有命名“单个文件”,它不会,那么即使文件存在,条件也会失败。
你可以这样检查。如果路径没有扩展,它将失败并退出。如果它找到至少一条好的路径,它将成功并退出。
for pf in $path_file_conf ; do
if [ -e "$pf" ] ; then
echo "Found"
break
else
echo "Not found"
fi
done
我会尝试这样的事情:
for filename in /fullpath/directory/*.conf
do
if [ -e "$filename" ] # If finds match...
then
echo "Found file"
echo
else
echo "No found file"
fi
done
我没有测试过,所以我不确定它是否有效,但它至少会给你整体策略。
造成麻烦的线路是:
path_file_conf=/full/path/directory/*.conf
当有多个要匹配的文件或没有匹配的文件时,shell 不会对名称进行通配符扩展,因此(除非在特殊情况下调用*.conf带有星号的文件)-e测试失败。bash当通配符匹配失败时,可能有一个选项可以生成错误;我永远不会使用它。
您可以使用:
path_file_conf=( /full/path/directory/*.conf )
这为您提供了一个数组,其中文件的名称作为数组的元素。但是,如果没有匹配的文件,它会为您提供作为数组唯一元素写入的名称。
从那里,您可以依次检查每个文件:
for conf_file in "${path_file_conf[@]}"
do
if [ -e "$conf_file" ]
then echo "Found file $conf_file"
else echo "No such file as $conf_file"
fi
done
您可以用 确定名称的数量${#path_file_conf[@]},但请记住,1 可能表示真实文件或不存在的文件。