bash - 使用递归 - 计算目录中的可执行文件
bash - using recursion - counting the executable files in dir
我不是在寻找一些高级答案,只有一行,我正在尝试制作一个可以工作的脚本并使其与递归一起工作并理解它:)
我正在尝试学习 bash 脚本编写,但遇到了一些问题:
我正在尝试计算一个目录及其子目录中可执行文件的数量
这就是我的想法
文件名 countFiles:
#!/bin/bash
counter = 0
for FILE in (/*) /// going over all the files in the input path
do
if (-d $FILE); then /// checking if dir
./countFiles $FILE /// calling the script again with ned path
counter= $($counter + [=11=]) /// addint to the counter the number of exe files from FILE
fi
if (-f $FILE); then /// checking if file
if (-x $FILE); then /// checking id exe file
counter = $counter + 1 // adding counter by 1
fi
fi
done
exit($counter) // return the number for exe files
如果你真的想使用递归(这在 Bash 中是个坏主意):首先,不要递归地调用你的脚本。相反,递归调用函数。这将更有效率(没有分叉开销)。正在尝试修复您的语法:
#!/bin/bash
shopt -s nullglob
count_x_files() {
# Counts number of executable (by user, regular and non-hidden) files
# in directory given in first argument
# Return value in variable count_x_files_ret
# This is a recursive function and will fail miserably if there are
# too deeply nested directories
count_x_files_ret=0
local file counter=0
for file in ""/*; do
if [[ -d $file ]]; then
count_x_files "$file"
((counter+=count_x_files_ret))
elif [[ -f $file ]] && [[ -x $file ]]; then
((++counter))
fi
done
count_x_files_ret=$counter
}
count_x_files ""
echo "$count_x_files_ret"
我不是在寻找一些高级答案,只有一行,我正在尝试制作一个可以工作的脚本并使其与递归一起工作并理解它:)
我正在尝试学习 bash 脚本编写,但遇到了一些问题:
我正在尝试计算一个目录及其子目录中可执行文件的数量
这就是我的想法
文件名 countFiles:
#!/bin/bash
counter = 0
for FILE in (/*) /// going over all the files in the input path
do
if (-d $FILE); then /// checking if dir
./countFiles $FILE /// calling the script again with ned path
counter= $($counter + [=11=]) /// addint to the counter the number of exe files from FILE
fi
if (-f $FILE); then /// checking if file
if (-x $FILE); then /// checking id exe file
counter = $counter + 1 // adding counter by 1
fi
fi
done
exit($counter) // return the number for exe files
如果你真的想使用递归(这在 Bash 中是个坏主意):首先,不要递归地调用你的脚本。相反,递归调用函数。这将更有效率(没有分叉开销)。正在尝试修复您的语法:
#!/bin/bash
shopt -s nullglob
count_x_files() {
# Counts number of executable (by user, regular and non-hidden) files
# in directory given in first argument
# Return value in variable count_x_files_ret
# This is a recursive function and will fail miserably if there are
# too deeply nested directories
count_x_files_ret=0
local file counter=0
for file in ""/*; do
if [[ -d $file ]]; then
count_x_files "$file"
((counter+=count_x_files_ret))
elif [[ -f $file ]] && [[ -x $file ]]; then
((++counter))
fi
done
count_x_files_ret=$counter
}
count_x_files ""
echo "$count_x_files_ret"