计算 shell 变量中的项目数

Hel*_*ene 2 shell

我有一个 shell 变量 sampleDir:

sampleDir=/home/sample*
echo $sampleDir
Run Code Online (Sandbox Code Playgroud)

会给:

/home/sample_001 /home/sample_002 /home/sample_003
Run Code Online (Sandbox Code Playgroud)

(注意sample_***下有子目录)

如果我想计算 $sampleDir 变量中有多少这些项目,请问最好的方法是什么?(预计返回3)

小智 5

将变量存储在数组中:

sampleDir=(/home/sample*)
Run Code Online (Sandbox Code Playgroud)

使用参数扩展来获取数组中的项目数:

echo "${#sampleDir[@]}"
Run Code Online (Sandbox Code Playgroud)