问题描述
我正在尝试做一个简单的 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 脚本中重置数字变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!