0

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

/var/www/html/images/myImage.jpg

Sometimes the image location is stored using the web location

http://192.168.1.2/images/myImage.jpg

Which fails in the linux command.

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

2

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:

path_to_file=images/myImage.jpg
if curl --head --location --silent --fail "http://192.168.1.2/$path_to_file" > /dev/null
then
    printf "%s exists\n" "$path_to_file"
else
    printf "%s does not exist\n" "$path_to_file"
fi

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).
| improve this answer | |
  • 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.