将目录中的文件数返回给shell脚本中的变量

时间:2015-01-14 12:16:08

标签: linux shell ubuntu

我需要目录中的总文件数,并希望在shell脚本中使用此数字。 我在终端试过这个并且工作正常:

find . -type f | wc -l

它只打印文件的数量,但我想将返回的数字分配给我的shell脚本中的变量,我试过这个,但它没有用:

numberOfFiles = find . -type f | wc -l;
echo $numberOfFiles;

2 个答案:

答案 0 :(得分:1)

要存储命令的输出,您需要使用var=$(command)语法:

numberOfFiles=$(find . -type f | wc -l)
echo "$numberOfFiles"

您当前的方法存在的问题:

numberOfFiles = find . -type f | wc -l;
             ^ ^
             | space after the = sign
             space after the name of the variable
      no indication about what are you doing. You need $() to execute the command

您目前正在尝试使用以下参数执行numberOfFiles命令:= find . -type f | wc -l;,显然不是您想要执行的操作:)

答案 1 :(得分:1)

尝试这一点,在将命令输出分配给需要使用`的变量时。或者您也可以使用$(command)。两者都是正确的方式。

numberOfFiles=`find . -type f | wc -l`;
echo $numberOfFiles;