I'm writing a program that uses a Linux command to check if a file exists on the local server.

The program executes a command with a supplied argument

ls *ARG_GOES_HERE* &> /dev/null

and then checks the status if it was able to find the file or not.

The problem is that sometimes the file is not a straight forward path like


Sometimes the image location is stored using the web location

Which fails in the linux command.

Is it possible to check if an image exists on a local apache location using bash?


You can use the curl command to check that the file exists and can be accessed via HTTP. Something like this should work for you:

if curl --head --location --silent --fail "$path_to_file" > /dev/null
    printf "%s exists\n" "$path_to_file"
    printf "%s does not exist\n" "$path_to_file"

The following curl options are used:

  • --head – only fetch the HTTP headers (there’s no need for the body)
  • --location – follow any HTTP redirects
  • --silent – don’t show progress meter or error messages
  • --fail – the curl commands fails with an error status if the HTTP request fails, e.g., if the web server responded with a 404, the curl commands exits with a status of 22 (error) instead of 0 (success).
  • 1
    I never thought of using curl, it seems to work perfectly – TheLovelySausage Jun 14 '16 at 14:56

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.