1

我有这个示例代码:

find "$1" ! -regex "$regex" 2>/dev/null | while read line ; do
    a="$line"
done

echo ("$a") # prints nothing because of subshell

我需要:

  • subshel​​l 使$a外部可见(在全局范围内)的解决方法
  • 不使用 bash 的进程替换
  • 兼容 dash、bash 和 korn shell

我怎样才能做到这一点?有没有简单的解决方案?

4

3 回答 3

5

如果我对您的理解正确,那么困扰您的不是子shell,而是变量在子shell之外没有保留其值的事实。您可以像这样使用代码分组:

find "$1" ! -regex "$regex" 2>/dev/null | 
{ 
  while read line
  do
    a=$line
  done
  echo "$a"
}

只要变量a在花括号内,您就可以使用它的值。

于 2016-04-09T06:55:46.987 回答
2

如果没有命名管道并且没有在子 shell 中运行整个内容,您可以在here-doc中使用带有命令替换的 here-doc:

while read line; do
    a=$line
done <<EOF
    $(find "$1" ! -regex "$regex" 2>/dev/null)
EOF

echo "$a"

这应该是便携式的。

也可以看看。 Bash常见问题解答/024

笔记。解析这样的输出find是一种反模式。

于 2017-12-19T08:46:24.630 回答
1

使用显式命名管道。

mkfifo named_pipe
find "$1" ! -regex "$regex" 2> /dev/null > named_pipe &

while read line; do
    a=$line
done < named_pipe
于 2016-03-28T18:31:24.007 回答