shell - 管道中变量的范围

标签 shell pipe

以下 shell 脚本将检查磁盘空间并更改变量 diskfull1如果使用率超过 10%
最后一个回显总是显示 0我试过 global diskfull=1在 if 子句中,但它不起作用。
如何将变量更改为 1如果消耗的磁盘超过 10%?

#!/bin/sh
diskfull=0

ALERT=10
df -HP | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output;
do
  #echo $output
  usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1  )
  partition=$(echo $output | awk '{ print $2 }' )
  if [ $usep -ge $ALERT ]; then
     diskfull=1
     exit
  fi
done

echo $diskfull

最佳答案

这是使用 while 的副作用在一个管道中。有两种解决方法:

1) 把 while循环及其在单独作用域中使用的所有变量,如 levislevis86 所示

some | complicated | pipeline | {
    while read line; do
        foo=$( some calculation )
    done
    do_something_with $foo
}
# $foo not available here

2) 如果您的 shell 允许,请使用 进程替换您可以将管道的输出重定向到 while 循环的输入
while read line; do
    foo=$( some calculation )}
done < <(some | complicated | pipeline)
do_something_with $foo

关于shell - 管道中变量的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1789750/

相关文章:

bash - Shell 脚本打印的值比我想要的多

c - 管道缓冲区大小是 4k 还是 64k?

c - 重定向标准流

shell - 在shell中执行umask命令时返回的002值是什么意思

bash - grepping 顶部输出时出现未知符号条目

shell - 如何解析Shell脚本中的字符串

c - dup2 是在 linux 终端中模拟命令序列行为的正确方法吗?

c - Select、pipe 和 waitpid - 如何等待特定的子进程?

c - parent 从文件中读取操作, child 将其与 bc 相加

java - Jenkins "execute shell command"段字符串参数的使用