我正在编写一个shell脚本,通过用户输入读取give目录中的所有文件,然后计算具有该扩展名的文件数。我刚刚开始学习Bash,我不确定为什么它不能找到文件或读取目录。我只提了两个例子,但我的计数总是0。
这是我运行脚本的方式
$./check_ext.sh /home/user/temp
我的脚本check_ext.sh
#!/bin/bash
count1=0
count2=0
for file in "ls $1"
do
if [[ $file == *.sh ]]; then
echo "is a txt file"
(( count1++ ))
elif [[ $file == *.mp3 ]]; then
echo "is a mp3 file"
(( count2++ ))
fi
done;
echo $count $count2
答案 0 :(得分:2)
"ls $1"
不会在ls
上执行$1
,它只是一个纯字符串。命令替换语法为$(ls "$1")
但是没有必要使用ls
,只需使用globbing:
count1=0
count2=0
for file in "$1"/*; do
if [[ $file == *.sh ]]; then
echo "is a txt file"
(( count1++ ))
elif [[ $file == *.mp3 ]]; then
echo "is a mp3 file"
(( count2++ ))
fi
done
echo "counts: $count1 $count2"
for file in "$1"/*
将遍历$1
编辑:在目录中递归执行:
count1=0
count2=0
while IFS= read -r -d '' file; do
if [[ $file == *.sh ]]; then
echo "is a txt file"
(( count1++ ))
elif [[ $file == *.mp3 ]]; then
echo "is a mp3 file"
(( count2++ ))
fi
done < <(find "$1" -type f -print0)
echo "counts: $count1 $count2"
答案 1 :(得分:1)
POSIXly:
count1=0
count2=0
for f in "$1"/*; do
case $f in
(*.sh) printf '%s is a txt file\n' "$f"; : "$((count1+=1))" ;;
(*.mp3) printf '%s is a mp3 file\n' "$f"; : "$((count2+=1))" ;;
esac
done
printf 'counts: %d %d\n' "$count1" "$count2"
答案 2 :(得分:0)
您也可以使用Bash数组:如果您只想处理扩展程序sh
和mp3
:
#!/bin/bash
shopt -s nullglob
shs=( "$1"/*.sh )
mp3s=( "$1"/*.mp3 )
printf 'counts: %d %d\n' "${#shs[@]}" "${#mp3s[@]}"
如果您想处理更多扩展程序,可以概括此过程:
#!/bin/bash
shopt -s nullglob
exts=( .sh .mp3 .gz .txt )
counts=()
for ext in "${exts[@]}"; do
files=( "$1"/*."$ext" )
counts+=( "${#files[@]}" )
done
printf 'counts:'
printf ' %d' "${counts[@]}"
echo
如果你想处理所有扩展(使用关联数组,可以在Bash中使用≥4)
#!/bin/bash
shopt -s nullglob
declare -A exts
for file in "$1"/*.*; do
ext=${file##*.}
((++'exts[$ext]'))
done
for ext in "${!exts[@]}"; do
printf '%s: %d\n' "$ext" "${exts[$ext]}"
done