不能在bash中增加一个variables

我正在尝试创build一个脚本来计算运行该脚本的文件夹中隐藏和非隐藏文件的数量。 但是,我碰到一个问题,我不能增加variables。

#!/bin/bash #A simple script to count the number of hidden and non-hidden files in the folder this script is run in #Variables to store the number of hidden and non-hidden files and folders #Variables with a 'h' at the end represent hidden items files=0 fileh=0 #List all files and folders #Use grep to folder entries beginning with '-', which are files #Return the 9th word in the string which is the filename #Read the filename into the variable 'fls' ls -al | grep ^- | awk '{print $9}' | while read fls #If the filename begins, with a dot, it is a hidden file do if [[ $fls == .* ]] then #Therefore increment the number of hidden files by one let fileh++ else #Else, increment the number if non-hidden files by one let files++ fi done #Print out the two numbers echo $files 'non-hidden files' echo $fileh 'hidden files' #When I run this script, the output is always zero for both variables #I don't know why this doesn't work?! 

这个脚本的输出如下:

 jai@L502X~$ ./script.sh 0 non-hidden files 0 hidden files 

Solutions Collecting From Web of "不能在bash中增加一个variables"

在|的右侧会发生什么? 发生在一个子shell。 子shell中对变量的更改不会传播回父shell。

常见的解决方法:不要使用管道,使用流程替换:

 while read fls ; do ... done < <(ls -al | grep ^- | awk '{print $9}') 

如果你想使用let增加一个变量,你必须引用你的表达式,就像

 let "i++" 

但是,我个人更喜欢使用双括号语法

 ((i++)) # or, if you want a pre-fixed increment ((++i)) 

另外,可以使用&&||来为if语句使用更短的语法 :

 [[ $fls == .* ]] && ((++fileh)) || ((++files)) 

不是“增量”问题的答案,而是一个更简单的脚本来做你正在做的事情:

 files=`find . -type f` echo "non-hidden files " `echo "$files" | egrep -v "[/]\.[^/]+$" | wc -l` echo "hidden files " `echo "$files" | egrep "[/]\.[^/]+$" | wc -l` 

引用可变增量

 let "fileh++"