本文介绍了无法在bash中增加变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个脚本来计算运行脚本的文件夹中隐藏和非隐藏文件的数量.但是,我遇到了无法递增变量的问题.
I'm trying to create a script to count the number of hidden and non-hidden files in a folder where the script is run.However, I run into an issue where I cannot increment 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
推荐答案
|
右侧发生的事情发生在子外壳中.对子Shell中的变量所做的更改不会传播回父Shell.
What happens on the right hand side of a |
happens in a subshell. Changes to variables in a subshell don't propagate back to the parent shell.
常见的解决方法:不要使用管道,而是使用流程替换:
Common workaround: don't use a pipe, use Process substitution:
while read fls ; do
...
done < <(ls -al | grep ^- | awk '{print $9}')
这篇关于无法在bash中增加变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!