Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.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
带有if[[!-f路径到文件]]的bash脚本_Bash_Macos_Terminal - Fatal编程技术网

带有if[[!-f路径到文件]]的bash脚本

带有if[[!-f路径到文件]]的bash脚本,bash,macos,terminal,Bash,Macos,Terminal,在MacOS Catalina上,我有一个bash脚本 if [[ ! -f $CR/home/files/Recovery_*.txt ]] then echo "File does not exists in /home/files directory. Exiting" >> $log echo "Aborted - $CR/home/files/Recovery_*txt not exist" exit fi 即使目录中有2个文件,脚本也会退出。如果我事先列出目

在MacOS Catalina上,我有一个bash脚本

if [[ ! -f $CR/home/files/Recovery_*.txt ]]
then
  echo "File does not exists in /home/files directory. Exiting" >> $log
  echo "Aborted - $CR/home/files/Recovery_*txt not exist"
  exit
fi
即使目录中有2个文件,脚本也会退出。如果我事先列出目录内容,则有2个文件。如果我按以下方式更改,则跳过If:

if [[ `ls -la $CR/home/files/Recovery_*.txt | wc -l` -eq 0 ]]
then
  echo "No files are :"
  exit
fi
我想使用if-f条件

有什么建议吗

干杯,C

[编辑] 错误不是变量,而是脚本在W2K3 SFU中遇到的缺少shebang

关于shellchecker.net的提示非常棒,我将从现在开始使用它


谢谢。

如果使用
nullglob
,则不匹配的glob表达式将返回空字符串。这使我们能够在bash中计算文件数量,而不会产生其他进程。使用表达式创建数组,然后检查其长度

shopt -s nullglob
files=($CR/home/files/Recovery_*.txt)
if [[ ${#files[@]} -eq 0 ]]
then
    echo "No files"
    exit
fi

我将您的代码粘贴到shellcheck.net中,发现“-f不适用于globs”建议,因为
[[-f..]]
不适用于globs我可能会将错误消息重定向到stderr并以非零状态退出(如果是在返回错误的命令后立即运行的,那么仅退出是正确的,但这里不是这样,因为我们不希望echo失败)。我同意。我们专注于条件,只是复制了OP的原始then子句。