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
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`.
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
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically