在循环shell脚本外部获取变量
我希望使用shell脚本获取while循环外部变量的内容 例如: :: $result每次都显示为空 我只希望结果的内容在循环之外 在这个问题上谁能帮忙!我知道循环中的变量是在子shell中执行的,但我尝试了几个技巧,但都不起作用在循环shell脚本外部获取变量,shell,Shell,我希望使用shell脚本获取while循环外部变量的内容 例如: :: $result每次都显示为空 我只希望结果的内容在循环之外 在这个问题上谁能帮忙!我知道循环中的变量是在子shell中执行的,但我尝试了几个技巧,但都不起作用 感谢avdance哇,您的短脚本中有大量语法错误。我在下面的注释中详细介绍了它们,并调整了变量的声明位置,以使循环执行某些操作,例如 #!/bin/sh count=5 ## no spaces aroung " = " a=3 ## a &
感谢avdance哇,您的短脚本中有大量语法错误。我在下面的注释中详细介绍了它们,并调整了变量的声明位置,以使循环执行某些操作,例如
#!/bin/sh
count=5 ## no spaces aroung " = "
a=3 ## a & b never change in loop
b=4
while [ "$count" -gt 0 ]; do ## always quote variables in [ .. ], spaces required
if ((a > b)); then ## there are two ((..)) in arithmetic comparison
result="UP" ## NO spaces around " = "
else
result="DOWN" ## ditto
fi
printf "%d %s\n" "$count" "$result" ## some output helps
count=$((count - 1)) ## use arithmetic ((..)), no $ required inside
((a++)) ## increment a to make it iteresting.
done
首先,在shell中,赋值期间“=”符号周围不允许有空格。当使用[…]时,必须在[和之前]后面留出空格,并始终在其中引用变量。bash[…]或算术比较不需要引用
每个if和elif后面必须跟一个then。每隔一个for或while后面必须跟一个do
使用算术运算符时。。无论是算术运算还是比较,都需要两个参数。您也可以使用递增和递减运算符++和-,例如a++来递增/递减内的值,但如果您指定的是结果,则必须在开始之前使用$,例如$count-1
示例使用/输出
我认为这是大多数语法问题的原因。如果您还有其他问题,请在下面发表评论。count=$count-1,但由于a和b从未改变,If[$a-gt$b]或a>b也从未改变。。。@count应该是$count-你需要在0]之间留一个空格。你丢了shell语法书吗?@CarlosH:在发布代码之前,请至少修复语法错误。另外,您需要更清楚地了解您使用的是什么shell:您的标签上写着“POSIX shell”,但您使用的是$[…],这是一个已经过时的bash构造。
#!/bin/sh
count=5 ## no spaces aroung " = "
a=3 ## a & b never change in loop
b=4
while [ "$count" -gt 0 ]; do ## always quote variables in [ .. ], spaces required
if ((a > b)); then ## there are two ((..)) in arithmetic comparison
result="UP" ## NO spaces around " = "
else
result="DOWN" ## ditto
fi
printf "%d %s\n" "$count" "$result" ## some output helps
count=$((count - 1)) ## use arithmetic ((..)), no $ required inside
((a++)) ## increment a to make it iteresting.
done
$ sh count.sh
5 DOWN
4 DOWN
3 UP
2 UP
1 UP