If you want to capture the HTTP status code in a variable, but still redirect the content to STDOUT, you must create two STDOUTs. You can do so with process substitution >() and command substitution $().
First, create a file descriptor 3
for your current process' STDOUT with exec 3>&1
.
Then, use curl's -o
option to redirect the response content to a temporary fifo using command substitution, and then within that command substitution, redirect output back to your current process STDOUT file descriptor 3
with -o >(cat >&3)
.
Putting it all together in bash
3.2.57(1)-release
(standard for macOS
):
#creates# creates a new file descriptor 3 that redirects to 1 (STDOUT)
exec 3>&1
# Run curl in a separate command, capturing output of -w "%{http_code}" into HTTP_STATUS
# and sending the content to this command's STDOUT with -o >(cat >&3)
HTTP_STATUS=$(curl -w "%{http_code}" -o >(cat >&3) 'http://example.com')
Note that this doesn't work in /bin/sh
as SamK noted in the comments below.