Getting a ‘command not found’ error when grepping HTTP codes in bash

0
11
Asked By CleverTornado98 On

Hey everyone! I'm trying to store the HTTP status code from a site and use it to check if the site is good or bad with `grep`. Here's the script I'm working on:

```
#!/bin/bash
http_code=$(curl -s -o /dev/null -w "%{http_code}" https://example.com/)

if $http_code | grep '404|301'; then
printf "bad"
else
printf "good"
fi
```

The `curl` command gets the HTTP code correctly when I run it directly, but when I store it in `$http_code`, I get an error saying `200: command not found`. I also tested another logic that works:

```
#!/bin/bash
if curl -s -o /dev/null -w "%{http_code}" https://example.com/ | grep -q '404|301'; then
printf "bad"
else
printf "good"
fi
```

Can anyone help me understand why I'm seeing the error with the stored variable? Thanks for any advice!

2 Answers

Answered By TechieNinja42 On

The issue is in this line: `if $http_code | grep '404|301'; then`. When you use `$http_code` like that, it tries to execute it as a command. So if `$http_code` is `200`, it looks for a command named `200`, which doesn't exist.

Instead, you should use `echo` to create output from the variable, like so: `if echo $http_code | grep '404|301'; then`. However, it's actually simpler to just compare the variable directly with `if [ "$http_code" = '404' ] || [ "$http_code" = '301' ]; then`.

Answered By CuriousCoder99 On

Right! And if you want to check if the site is bad (meaning it's 404 or 301), it’s way more efficient to just use a simple comparison, like this:

```
if [ "$http_code" = '404' ] || [ "$http_code" = '301' ]; then
printf "bad"
else
printf "good"
fi
```
This cuts out the need for `grep` completely while keeping your check straightforward!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.