Jams
Jams

Reputation: 4067

if condition in shell scripting based on 404 unauthorized error

Here is my shell script. I want to put a condition to my curl commands based on the status i get. I need help in grepping "Http/1.1 401 Unauthorized" from the first curl command. After that i need to put it in a condition if status is 401, execute 2nd and 3rd curl command. Pls help

STATUS="HTTP/1.1 401 Unauthorized"
read $STATUS

for ((i=1; i<=2000; i++)); do
curl -i -vs -X POST -D post.txt -H "$SESSION_TOKEN" -H "$AUTH_TOKEN" -H "Accept:$ACCEPT_HEADER" -H "Content-Type:text/plain" "http://$BASE_URI/api/$PLATFORM//$CHANNEL_ID/subscription" | grep -e "*Unauth*" >> post.txt

if [$STATUS]
then
curl -i -vs -X POST -D tmp.txt -H "Content-Type:text/plain" --data "$SECRET" -H "Accept:$ACCEPT_HEADER" -H "Connection:close" http://$BASE_URI/api/${PLATFORM}/authenticate >> tmp1.txt
SESSION_TOKEN=`grep SessionToken tmp.txt`

curl -i -vs -X POST -D tmp2.txt -H "$SESSION_TOKEN" -H "Content-Type:text/plain" -H "Content-Type:application/json" --data "{ \"username\":\"$USER_NAME\",\"password\":\"$PASSWORD\", \"rememberMe\":\"false\"}" http://$BASE_URI/api/web/users/authenticate >> data.json
AUTH_TOKEN=`grep Authorization tmp2.txt`

continue

fi

done

Upvotes: 1

Views: 2998

Answers (2)

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185530

The proper solution :

res=$(curl -s -o /dev/null -w '%{http_code}\n' http://google.fr)
if ((res == 404)); then
    echo "404 spotted"
fi 

or

res=$(curl -s -o /dev/null -w '%{http_code}\n' http://google.fr)
if [[ $res == 404 ]]; then
    echo "404 spotted"
fi 

Check

man curl | less +/'^ *-w'

Upvotes: 4

glenn jackman
glenn jackman

Reputation: 247012

You have to capture the curl output and examine the status line:

output=$( curl -i ... )

if [[ $output == "$STATUS"* ]]; then
    # I was unauthorized
else
    # ...
fi

Be aware that [ (and [[ I use in my answer) is not mere syntax, it is a command, and as such it requires a space between it and its arguments

Upvotes: 0

Related Questions