[英]Cannot increment a variable in bash
我正在尝试创建一个脚本来计算运行脚本的文件夹中隐藏和非隐藏文件的数量。 但是,我遇到了无法递增变量的问题。
#!/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
|
的右侧发生了什么? 发生在子外壳中。 对子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))
引用变量增量
let "fileh++"
不是“增加”问题的答案,而是一个简单得多的脚本来完成您要执行的操作:
files=`find . -type f`
echo "non-hidden files " `echo "$files" | egrep -v "[/]\.[^/]+$" | wc -l`
echo "hidden files " `echo "$files" | egrep "[/]\.[^/]+$" | wc -l`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.