检查它是否存在脚本中的文件

所以我有一个文件名bobv1.txt,我不想手动检查以查看bobv2.txt是否在网站上。 在网站上bobv1.txt将被bobv2.txt取代。 我已经下载了html页面并确定了bobvX.txt的完整下载路径,我知道该文件在我的文件系统中。 如何判断文件是否已存在于我的文件系统中? 我需要这个适用于所有后续版本。

如果您需要shell脚本,那么您可以使用:

#!/bin/bash file="$1" if [ -f "$file" ]; then echo "File $file exists." else echo "File $file does not exist." fi 

你可以像这样运行它:

 bash test.sh /tmp/bobv2.txt 

有很多方法可以检查文件是否存在。

  • 使用test命令(又名[ [ -f /path/to/file.txt ]来做[ -f /path/to/file.txt ]
  • 使用重定向尝试打开文件(请注意,如果您缺少读取所述文件的权限,则此方法无效)

     $ bash -c 'if < /bin/echo ;then echo "exists" ; else echo "does not exist" ; fi' exists $ bash -c 'if < /bin/noexist ;then echo "exists" ; else echo "does not exist" ; fi' $ bash: /bin/noexist: No such file or directory does not exist 

    或者沉默错误消息:

     $ 2>/dev/null < /etc/noexist || echo "nope" nope 
  • 使用stat等外部程序

     $ if ! stat /etc/noexist 2> /dev/null; then echo "doesn't exist"; fi doesn't exist 

    find命令:

     $ find /etc/passwd /etc/passwd $ find /etc/noexist find: '/etc/noexist': No such file or directory