Skip to content
Advertisement

How can this bash script be made shorter and better? Is there a way to combine multiple curl statements and if statements in bash?

Status_code_1=$(curl -o /dev/null -s -w "%{http_code}n" -H "Authorization: token abc123" https://url_1.com)
Status_code_2=$(curl -o /dev/null -s -w "%{http_code}n" -H "Authorization: token abc123" https://url_2.com)

if [ $Status_code_1  == "200" ]; then
    echo "url_1 is running successfully"
else
    echo "Error at url_1. Status code:" $Status_code_1
fi

if [ $Status_code_2 == "200" ]; then
    echo "url_2 is running successfully"
else
    echo "Error Error at url_2. Status code:" $Status_code_2
fi

The main script is scheduled and runs everyday and prints the success message everytime. If the status code is anything other than 200, $Status_code_1 or $Status_code_2, whichever is down prints the error code.

The code is working fine but I want to know how can it be made shorter. Can the curl command from first 2 lines be combined because they have same authorization and everything, it’s just the url at the end is different. Also later if statements are pretty much same, only that I’m running them separately for different urls.

Is it possible to write first 2 lines in one line and same for both if statements? I know AND and OR can be used for if statements but say we have 5 urls and 2 are down, how it will print the name of those 2 urls in that case?

Advertisement

Answer

Is there a way to combine multiple curl statements and if statements in bash?

curl can retrieve multiple URLs in one run, but then you’re left to parse its output into per-URL pieces. Since you want to report on the response for each URL, it is probably to your advantage to run curl separately for each.

But you can make the script less repetitive by writing a shell function that performs one curl run and reports on the results:

test_url() {
  local status=$(curl -o /dev/null -s -w "%{http_code}n" -H "Authorization: token abc123" "$1")

  if [ "$status" = 200 ]; then
    echo "$2 is running successfully"
  else
    echo "Error at $2. Status code: $status"
  fi
}

Then running it for a given URL is a one-liner:

test_url https://url_1.com url1_1
test_url https://url_2.com url1_2

Altogether, that’s also about the same length as the original, but this is the break-even point on length. Each specific URL to test requires only one line, as opposed to six in your version. Also, if you want to change any of the details of the lookup or status reporting then you can do it in one place for all.

Advertisement