linux - 无法在 bash 中增加变量

标签 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

最佳答案

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

let "i++"

不过,我个人更喜欢使用双括号语法,也就是

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

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

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

关于linux - 无法在 bash 中增加变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27677757/

相关文章:

regex - 修剪目录中所有文件的一部分文件扩展名 - Linux

c++ - 将指针分配给特定内存地址并更改其值后出现段错误

linux - 使用 printf 创建标题

点开头目录的 Bash 模式,不包括 .和

c++ - 为什么 int count 在进入循环时从 1 跳到 4? C++

c - 使用 Linux 套接字检测 TCP 重置

bash - 如何使用不同目录中的多个窗口启动 tmux?

bash - 计算 Bash 中 Docker 容器使用的总内存

c - 递增字符指针

javascript - 如何从 forEach 方法中删除不需要的计数增量?