Checking it see if a file exists in a script

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

2 Answers

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
0

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
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like