How do I return variables from curly braces?
For example, how do I get the return value of the command curl
outside the curly brackets in the following snippet?
#!/usr/bin/bash
{ # scope for tee
curl --max-time 5 "https://google.com"
rc=$?
} | tee "page.html"
echo "return code: $rc"
The reason $rc
is not updated in your example is because bash will create a subshell when using a pipe
One solution to your problem is to use ${PIPESTATUS[@]}
:
#!/usr/bin/bash
curl --max-time 5 "https://google.com" | tee "page.html"
echo "curl return code: ${PIPESTATUS[0]}"
Another solution is to not use a pipe at all avoiding the subshell for curl:
#!/usr/bin/bash
{ # scope for tee
curl --max-time 5 "https://google.com"
rc=$?
} > >( tee "page.html" )
echo "return code: $rc"