0

Consider this script:

#!/bin/bash

test() {
    local x='a';

    echo 'b' | {
        read x;
        echo "x (should be 'b'): ${x}"
    }

    echo "x (should be 'b'): ${x}";
}

test

As you can see, x is initialized to 'a' and then within the block it's set to 'b' as that is what's piped to the block. After the block, the value of x is still 'a' rather than the expected 'b'. What's missing here?

Note: this is a simple reproduction, in reality this is used to gather the response and status code from a curl command, e.g.:

curl --write-out '\n%{http_code}' ... | {
    read responseBody;
    read responseCode;
}

# use ${responseBody} and ${responseCode} here...

(It's intended for use in testing where the response body is either empty or a single line.)

Josh M.
  • 26,437
  • 24
  • 119
  • 200
  • The last command of a pipe executes in a new process, so `read` creates a new variable `x`that goes out of scope when that process exits. – chepner Mar 17 '23 at 12:50
  • I tried to `export x` as well but I assume that doesn't work since it's in a separate shell? – Josh M. Mar 17 '23 at 12:53
  • `export` is used to set variables in the environment *of* a new process; it cannot be used to affect the *parent* of the process doing the exporting. – chepner Mar 17 '23 at 12:54
  • Thank you. I rewrote this to include the `echo` (`curl`) command within the braces and/or a separate function, to remove the pipe. I'll submit my own answer unless you wanted to provide one. – Josh M. Mar 17 '23 at 13:03
  • In addition to being a perennial duplicate here, this is [BashFAQ #24](https://mywiki.wooledge.org/BashFAQ/024). – Charles Duffy Mar 17 '23 at 13:52
  • (As an aside, the `function` keyword is best avoided -- see both relevant entries in https://wiki.bash-hackers.org/scripting/obsolete; `function test() {` merges legacy ksh syntax `function test {` and modern POSIX syntax `test() {` in a way that's incompatible with _both_ legacy ksh and POSIX sh). – Charles Duffy Mar 17 '23 at 13:52
  • Yes, I don't use `function`, just put it there by accident in the example.Thanks. – Josh M. Mar 17 '23 at 15:19

0 Answers0