0

由于某种原因, hello2 函数不会更改 b 参数。

#!/bin/bash

function hello1 {
  a=hello1A
}

function hello2 {
  while read -a line; do
    echo ${line[*]}
  done

  b=hello2B
}

a=mainA
b=mainB

echo $a
echo $b
hello1
echo some text | hello2
echo $a
echo $b

它打印:

mainA
mainB
some text
hello1A
mainB

但我也想改变 b :

mainA
mainB
some text
hello1A
hello2B <----- !
4

1 回答 1

8

hello2函数在子shell中被调用,它只改变子shell中变量的值。如果要更新,请不要使用管道。你可以做:

hello2 << EOF
some text
EOF

或(不太便携)

hello2 <<< 'some text'

如果“某些文本”不是文字,而是命令的输出,您还可以这样做:

hello2 << EOF
$( cmd )
EOF

或(不太便携):

hello2 < <(cmd)

另一种选择是让 subshel​​l 存活更长的时间并执行以下操作:

echo some text | { hello2
echo $a
echo $b
}

但请注意,$b块结束后将恢复为原始值。

于 2013-05-26T14:32:29.840 回答