While 循环在 Bash 脚本中重置数字变量 [英] While loop resets a numeric variable in a Bash script

查看:31
本文介绍了While 循环在 Bash 脚本中重置数字变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一个简单的 bash 脚本来在一组文件夹中的每个文件中做一些事情.另外我喜欢统计脚本读取了多少文件,但是当脚本通过循环时,数值变量被重置.

I'm trying to do a simple bash script to do something in one of each file in a set of folders. Also I like to count how many files the script read, but when the script pass of the loop, the numerical variable is reseted.

我使用的代码是这样的

#!/bin/bash
let AUX=0
find . -type "f" -name "*.mp3" | while read FILE; do
    ### DO SOMETHING with $FILE###
    let AUX=AUX+1
    echo $AUX
done
echo $AUX

我可以看到 AUX 在循环内部计数,但是最后一个echo"打印了 0,并且变量似乎真的被重置了.我的控制台输出就是这样

I can see that AUX is counting inside the loop, but the last "echo" prints a 0, and the variable seems to be really reseted. My console output is like that

...
$ 865
$ 866
$ 867
$ 868
$ 0

我想在 AUX 中保留处理的文件数.有什么想法吗?

I would like to preserve in AUX the number of files proccesed. Any idea?

推荐答案

不要使用管道,它会创建一个子shell.示例如下.

Do not use the pipe, it creates a subshell. Example below.

#!/bin/bash
declare -i AUX=0
while IFS='' read -r -d '' file; do
    ### DO SOMETHING with $file###
    (( ++AUX ))
    echo $AUX
done < <(find . -type "f" -name "*.mp3")
echo $AUX

这篇关于While 循环在 Bash 脚本中重置数字变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆