无法在bash中增加变量

时间:2014-12-28 15:24:44

标签: linux bash increment

我正在尝试创建一个脚本来计算运行脚本的文件夹中隐藏和非隐藏文件的数量。 但是,我遇到了一个无法增加变量的问题。

#!/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

4 个答案:

答案 0 :(得分:1)

|右侧发生的事情发生在子shell中。对子shell中变量的更改不会传播回父shell。

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

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

答案 1 :(得分:1)

如果要使用let增加变量,则必须引用表达式,如

let "i++"

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

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

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

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

答案 2 :(得分:0)

引用变量增量

let "fileh++"

答案 3 :(得分:0)

不是&#34;增量的答案&#34;问题,但更简单的脚本来做你正在尝试做的事情:

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