To check the HTTP response code after running a curl command, you can use the -w option with curl, which allows you to specify a custom output format. Here’s the command:
curl -o /dev/null -s -w "%{http_code}\n" <URL>
You can save the HTTP response code into a BASH variable, like this:
resp=$(curl -o /dev/null -s -w "%{http_code}\n" <URL>)
Explanation:
- -o /dev/null: Discards the output of the response body.
- -s: Runs curl in silent mode (no progress or error messages).
- -w “%{http_code}\n”: Outputs only the HTTP response code.
Replace <URL> with the actual URL you’re checking.
How to Get HTTP Response Code and Output?
To get the http output at the same time, you would need to use -o to redirect the output. For example:
resp=$(curl -s -w "%{http_code}" -o /tmp/curl_output.txt <URL>)
And the BASH variable $resp contains the HTTP response code, and the /tmp/curl_output.txt contains the request output.
BASH Programming/Shell
- Alarming on High Disk Usage using BASH, AWK, Crontab Job
- Compute GCD in Bash with Input Validation
- Why a Leading Space in Linux Shell Commands Can Matter?
- How to Get HTTP Response Code using cURL Command?
- Three Interesting/Fun BASH Commands
- One Interesting Linux Command (Steam Locomotive in BASH)
- Simple Bash Function to Repeat a Command N times with Retries
- How to Extract a Domain Name from a Full URL in BASH?
- BASH Function to Compute the Greatest Common Divisor and Least Common Multiples
- BASH Function to Get Memory Information via AWK
- BASH Function to Escape Parameters Argument
- BASH Function to Check if sudo Available
- Full Permutation Algorithm Implementation in BASH
- BASH Function to Install Docker
- A Simple BASH Function/Script to Run a Command in Background
- BASH Script to Compute the Average Ping to a Domain
- A Bash Process Controller to Start, Stop and Restart an Daemon Program
- Linux BASH shell - Echo This if you get angry
- Bash SHELL, Chess Board Printing
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: Teaching Kids Programming - Compute the Range Sum with Update: A Deep Dive into Segment Tree, SQRT Decomposition, Brute Force & Prefix Sum
Next Post: Toss a Coin 256 Times: The Math Behind an Unbreakable Bitcoin Private Key