Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Shell脚本中将目录设置为变量_Shell_Unix_Ls - Fatal编程技术网

在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中运行嵌套命令,需要使用$

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

例如,当执行程序时

./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"