-2

So I have a filename bobv1.txt, and I don't want to manually check to see if bobv2.txt is on the site. On the site bobv1.txt will be replaced by bobv2.txt. I have downloaded the the html page and determined the full download path of bobvX.txt and I know were the file is in my file system. How can I tell if the file is already on my file system? I need this to work for all subsequent versions.

2 Answers2

4

If you need a shell script then you can use this:

#!/bin/bash
file="$1"

if [ -f "$file" ]; then
    echo "File $file exists."
else
    echo "File $file does not exist."
fi

You can run it like this:

bash test.sh /tmp/bobv2.txt
wjandrea
  • 14,236
  • 4
  • 48
  • 98
pl_rock
  • 11,297
2

There's plenty of ways to perform a check on whether or not a file exists.

  • use test command ( aka [ ) to do [ -f /path/to/file.txt ]
  • use redirection to attempt to open file ( note that this isn't effective if you lack permissions to read the said file)

    $ 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
    

    or with silencing the error message:

    $ 2>/dev/null < /etc/noexist || echo "nope"                                                                                                                            
    nope
    
  • use external program such as stat

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

    or find command:

    $ find /etc/passwd
    /etc/passwd
    
    $ find /etc/noexist
    find: ‘/etc/noexist’: No such file or directory
    
Sergiy Kolodyazhnyy
  • 105,154
  • 20
  • 279
  • 497