小编Joe*_*ran的帖子

Solaris 上 while-read-loop 中的变量范围

有人可以向我解释为什么我的 while 循环似乎有一个内部范围吗?我在网上看到了多种解释,但它们都与管道有关。我的代码没有。

编码:

#!/bin/sh
while read line
do
  echo "File contents: $line"
  echo
  if [ 1=1 ]; then
    test1=bob
  fi
  echo "While scope:"
  echo "  test1: $test1"
done < test.txt

if [ 1=1 ]; then
  test2=test2;
fi

echo;
echo "Script scope: "
echo "  test1: $test1"
echo "  test2: $test2"
Run Code Online (Sandbox Code Playgroud)

输出:

File contents: In the file

While scope:
  test1: bob

Script scope:
  test1: 
  test2: test2
Run Code Online (Sandbox Code Playgroud)

solaris shell-script variable bourne-shell

4
推荐指数
1
解决办法
2575
查看次数

标签 统计

bourne-shell ×1

shell-script ×1

solaris ×1

variable ×1