检查文件是否存在,以防某些文件包含 [ Bash
Check if files exist in case some files contain [ Bash
我有一组文件,比方说
file1.txt
File2.txt
File [3].txt
file 4.txt
在我的脚本中,我将每个文件的路径存储在一个名为 $file 的变量中。
这是我的问题:
在 bash 中,使用以下命令测试它是否存在
[[ ! -f "$file" ]]
对于常规文件(如
file1.txt
File2.txt
文件 4.txt 但不会工作(= 系统找不到该文件 - 因为它不存在)其中包含 [ ] 的文件,就像文件 [3].txt 一样。
我想是因为 [ ] 干扰了双 [[.使用
进行测试
test ! -f "$file"
一样,系统看不到它和return一个丢失的文件。
我该怎么做才能避免 [ 或避免这种行为?我试图在网上找到解决方案,但是当我键入“检查文件是否存在且文件名包含 [”时,存在偏差,因为 [ / [[ 用于检查是否存在..
感谢您的帮助!
编辑 - 2022-01-15
这是我正在使用的循环
while read -r file; do
if [[ ! -f "$file" ]]; then
echo "Missing file $file"
fi
done < Compil.all ;
其中 Compil.all 是包含文件路径的文本文件:
$cat Compil.all
/media/veracrypt1/file1.txt
/media/veracrypt1/File2.txt
/media/veracrypt1/File [3].txt
/media/veracrypt1/file 4.txt
$
因为我不想在文件名中出现 space 问题,所以我将以下代码放在脚本的开头。会不会是这个原因?
IFS=$(echo -en "\n\b")
您如何存储 file
变量?
简单的迭代工作如下所示:
$ ls
file1.txt File2.txt 'File [3].txt' 'file 4.txt'
$ for file in ./* ;do if [[ -f "$file" ]];then echo $file; fi; done
./file1.txt
./File2.txt
./File [3].txt
./file 4.txt
这也有效:
$ [[ ! -f "File [3].txt" ]]
$ echo $?
1
我有一组文件,比方说
file1.txt
File2.txt
File [3].txt
file 4.txt
在我的脚本中,我将每个文件的路径存储在一个名为 $file 的变量中。 这是我的问题: 在 bash 中,使用以下命令测试它是否存在
[[ ! -f "$file" ]]
对于常规文件(如 file1.txt File2.txt 文件 4.txt 但不会工作(= 系统找不到该文件 - 因为它不存在)其中包含 [ ] 的文件,就像文件 [3].txt 一样。
我想是因为 [ ] 干扰了双 [[.使用
进行测试test ! -f "$file"
一样,系统看不到它和return一个丢失的文件。
我该怎么做才能避免 [ 或避免这种行为?我试图在网上找到解决方案,但是当我键入“检查文件是否存在且文件名包含 [”时,存在偏差,因为 [ / [[ 用于检查是否存在..
感谢您的帮助!
编辑 - 2022-01-15 这是我正在使用的循环
while read -r file; do
if [[ ! -f "$file" ]]; then
echo "Missing file $file"
fi
done < Compil.all ;
其中 Compil.all 是包含文件路径的文本文件:
$cat Compil.all
/media/veracrypt1/file1.txt
/media/veracrypt1/File2.txt
/media/veracrypt1/File [3].txt
/media/veracrypt1/file 4.txt
$
因为我不想在文件名中出现 space 问题,所以我将以下代码放在脚本的开头。会不会是这个原因?
IFS=$(echo -en "\n\b")
您如何存储 file
变量?
简单的迭代工作如下所示:
$ ls
file1.txt File2.txt 'File [3].txt' 'file 4.txt'
$ for file in ./* ;do if [[ -f "$file" ]];then echo $file; fi; done
./file1.txt
./File2.txt
./File [3].txt
./file 4.txt
这也有效:
$ [[ ! -f "File [3].txt" ]]
$ echo $?
1