在Shell脚本

时间:2018-03-18 10:44:38

标签: shell unix ls

我要做的是使用shell脚本计算目录中的所有文件。

例如,执行程序时,

./test.sh project

它应该计算名为“project”的文件夹中的所有文件。

但我在目录部分遇到问题。

到目前为止,我所做的是,

#!/bin/bash

directory=$1
count=ls $directory | wc -l
echo "$folder has $count files"

但是它不起作用...有人可以炸掉我的困惑吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

设置计数时语法不正确,要在sf::Text中运行嵌套命令,需要使用bash使用命令替换,$(..)运行子shell中的命令并返回restult < / p>

count=$(ls -- "$directory" | wc -l)

但是出于任何目的从不在脚本中解析ls输出,请使用更通用的find命令

find "$1" -maxdepth 1 -type f  | wc -l 

详细了解$(..)表格Wiki Bash Hackers - Command substitution

的详情

答案 1 :(得分:0)

#!/bin/bash

directory=$1
count=`ls $directory | wc -l`

echo "$folder has $count files"