在Shell脚本中将目录设置为变量
我试图做的是使用shell脚本计算目录中的所有文件 例如,当执行程序时在Shell脚本中将目录设置为变量,shell,unix,ls,Shell,Unix,Ls,我试图做的是使用shell脚本计算目录中的所有文件 例如,当执行程序时 ./test.sh project 它应该统计名为“project”的文件夹中的所有文件 但是我在目录部分遇到了问题 到目前为止,我所做的是 #!/bin/bash directory=$1 count=ls $directory | wc -l echo "$folder has $count files" 但它不起作用。。。谁能把我的困惑发泄出来吗 谢谢 设置计数时语法不正确,要在bash中运行嵌套命令,需要使用$
./test.sh project
它应该统计名为“project”的文件夹中的所有文件
但是我在目录部分遇到了问题
到目前为止,我所做的是
#!/bin/bash
directory=$1
count=ls $directory | wc -l
echo "$folder has $count files"
但它不起作用。。。谁能把我的困惑发泄出来吗
谢谢 设置计数时语法不正确,要在
bash
中运行嵌套命令,需要使用$(..)
使用命令替换,它在子shell中运行命令并返回result
count=$(ls -- "$directory" | wc -l)
但千万不要出于任何目的解析脚本中的ls
输出,请使用更通用的find
命令
find "$1" -maxdepth 1 -type f | wc -l
查看更多有关
$(..)
表单的信息查找$(
)
(或反勾号)的功能。这称为命令替换。如果您使用的是bash,您还应该熟悉进程替换。如果您使用的目录名称以-
@melpomene开头,那么应该是ls-“$directory”
:根据我的更新,这不是我推荐的,但会使编辑仍然非常感谢您,顺便问一下,你能告诉我“$”是什么吗?为什么我们要在(ls…)前面放美元?@YooSungKyung:你应该通过我共享的链接Hanks!当我使用count=$(ls--“$directory”| wc-l)时,计数的文件是4个,但应该是3个,它是否也计算任何隐藏的文件?
#!/bin/bash
directory=$1
count=`ls $directory | wc -l`
echo "$folder has $count files"