奇怪的bash范围规则使我望而却步
发布时间:2020-12-15 22:23:42 所属栏目:安全 来源:网络整理
导读:考虑: t=0 ; for i in 1 2 3 4 5 6 7 8 9 10 ; do t=$((t+i)) ; done ; echo $t 打印55. 但: totsize=0find /home/user -type f -mmin -4860 -a -mmin +3420 | xargs du | while read size rest ; do totsize=$((totsize+size)) echo "$totsize"doneecho
考虑:
t=0 ; for i in 1 2 3 4 5 6 7 8 9 10 ; do t=$((t+i)) ; done ; echo $t 打印55. 但: totsize=0 find /home/user -type f -mmin -4860 -a -mmin +3420 | xargs du | while read size rest ; do totsize=$((totsize+size)) echo "$totsize" done echo "Sum: $totsize kb" 即使临时打印语句打印一个合理的总和,也打印“Sum:0 kb”. 我知道我之前遇到过这个问题,但从未理解过.有什么区别? 解决方法
这是因为管道创建了一个子shell,因此totsize在子shell中是“本地的”.你可以尝试这个(bash)
totsize=0 while read size rest ; do totsize=$((totsize+size)) echo "$totsize" done < <(find /home/user -type f -mmin -4860 -a -mmin +3420 | xargs du) echo "Sum: $totsize kb" 或者不是使用bash,而是调用awk $> find /home/user -type f -mmin -4860 -a -mmin +3420 | xargs du | awk '{s+=$1}END{print "total size: "s}' 但是你确定你想要使用du而没有任何选项,因为大小不是“准确”(使用du -b会更好).如果你有GNU find,你可以使用-printf find /home/user -type f -mmin -4860 -a -mmin +3420 -printf "%sn" | awk '{s+=$1}END{print "total size: "s" bytes"}' (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |