linux - 将目录中的文件数返回到 shell 脚本中的变量

标签 linux shell ubuntu

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

find . -type f | wc -l

它只是打印文件的数量,但我想将返回的数字分配给我的 shell 脚本中的一个变量,我试过了,但它不起作用:

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

最佳答案

要存储命令的输出,需要使用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 。 -类型f | wc -l;,这显然不是你想要做的:)

关于linux - 将目录中的文件数返回到 shell 脚本中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27942749/

相关文章:

html - 查找所有扩展名为 .md 的文件并使用该文件执行命令并生成一个新文件,其名称通过 md 文件名生成

linux - 有人可以详细解释这个简短的bash脚本做什么吗?

python - 在 Pycharm (Ubuntu 16) 中使用 Tensorflow virtualenv 时出错

ubuntu - GPG : ify: skipped: public key not found when I made the encryption myself

python - C 编译器从各种 unix 风格的源代码构建 python

linux - linux CFS 调度程序如何防止具有非常小的 vruntime 的任务使处理器挨饿?

linux - DNU 恢复失败,https GET 超时

bash - 在 shell 脚本中隐藏密码

linux - 为什么 tcpdump 的输出行为与三次握手的定义不同

PHP 代码未执行,PHP 新手