Shell Script to Detect a Redirected URL

I am not familiar with shell scripts (At All). So I somewhat hacked this code based on some web searching.

	set serverResponse to (do shell script "curl -Ls -w \"%{url_effective}\\n\" [url=]"[/url] & logoID & " -o /dev/null")
	if serverResponse contains ".jpg" then set fileExists to true
end try

The code above does work, and my variable serverResponse will return the full url, whether or not it is a redirect or not.

But I was wondering if anybody knew of a way to speed this up? At times there can be up to 2 minute delay for this shell script to finish? I was told that maybe there is a way to detect the 302 redirect on the initial URL?

In short I want to see if “” is a legitimate url. If the “xxxxxxxx.jpg” does not exist on our server then the url gets redirected. In short, I need to detect the presence of a logo that’s already out there, e.g., “The logo you are uploading already exists.”

Any help would be greatly appreciated.


Hey Jeff,

Fiddling with your script here I get the original URL returned even if it does not exist on the server.

If memory serves a redirect is a pointer on a particular server to re-direct a file-request to another server. There’s no way to tell from the beginning of that daisy chain just how many hops there will ultimately be.

You can turn off redirects (-L) and find out if there is a redirect at the beginning of the chain.

Okay, try this handler. It returns the remote file header, and you can parse that for what you need. If the file doesn’t exist the header should contain an error message (but I haven’t tested thoroughly).

Whups. It occurs to me that multiple redirects might produce a header for each hop, but I don’t have a handy redirected remote-file to test with.

Some servers don’t like curl or de-prioritize it, so we’ll provide a user-agent string that makes curl look like Opera.

set _url to ""

set remoteFileHeader to curlHeader(_url)

on curlHeader(_url)
	set _cmd to "curl -Ls -A 'Opera/9.70 (Linux ppc64 ; U; en) Presto/2.2.1' -I " & quoted form of _url
	do shell script _cmd
end curlHeader

You can play with the maximum time switch if you really need a time limit.

-m, --max-time
Maximum time in seconds that you allow the whole operation to take.