Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return variables from a curly brackets scoped code?

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"
like image 783
crackpot Avatar asked Nov 03 '25 22:11

crackpot


1 Answers

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"
like image 52
izissise Avatar answered Nov 05 '25 14:11

izissise



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!