【问题标题】:File count in a folder not showing accurate文件夹中的文件数显示不准确
【发布时间】:2021-07-18 06:54:35
【问题描述】:

我正在编写一个 shell 脚本来一次检查两件事。第一个条件是检查特定文件是否存在,第二个条件是确认该目录中只有一个文件。

我正在使用以下代码:

conf_file=ls -1 /opt/files/conf.json 2>/dev/null | wc -l 
total_file=ls -1 /opt/files/* 2>/dev/null| wc -l

if [ $conf_file -eq 1 ] && [ $total_file -eq 1 ]
then
    echo "done"
else
    echo "Not Done"
fi

返回以下错误

0
0
./ifexist.sh: 4: [: -eq: unexpected operator
Not Done

我可能犯了一个非常愚蠢的错误。谁能帮帮我?

【问题讨论】:

标签: bash shell command-substitution


【解决方案1】:

您通常不应该解析ls 的原因之一是当您的文件带有换行符时会得到奇怪的结果。在您的情况下,这不会成为问题,因为任何不同于 json.conf 的文件都应该使测试失败。但是,您应该使计算文件的代码面向未来。您可以为此使用find

你的代码可以改成

jsonfile="/opt/files/conf.json"
countfiles=$(find /opt/files -maxdepth 1 -type f -exec printf '.\n' \; | wc -l)

if [[ -f "${jsonfile}" ]] && (( "${countfiles}" == 1)); then
  echo "Done"
else
  echo "Not Done"
fi 

【讨论】:

    【解决方案2】:

    当你这样说时:

    conf_file=ls -1 /opt/files/conf.json 2>/dev/null | wc -l
    

    这会将值“ls”分配给变量conf_file,然后尝试运行名为“-1”的命令并将结果通过管道传输到wc 如果要运行管道序列,则必须包含它在 $( ) 中:

    conf_file=$(ls -1 /opt/files/conf.json 2./dev/null | wc -l)
    

    接下来,在test 命令([)中组合子句时,在命令内部进行:

    if [ $conf_file -eq 1 -a $total_file -eq 1 ]
    

    但是,有更好的方法可以做到这一点。您可以使用“-f”检查文件是否存在,您可以只检查ls 的输出是否与您的期望相符,而无需创建变量或运行其他命令:

    if [ -f /opt/files/conf.json -a "$(ls /opt/files/conf.*)" -eq "/opt/files/conf.json" ]
    

    但是,禁止其他文件不是一种友好的做法。在许多情况下,人们可能希望留下备份或测试副本(conf.json.bak 或 conf.json.test),您没有理由阻止它。

    【讨论】:

    • @tripleee 实际上不是这样。 xxx=/opt/files/no.such.file 将产生一个字符串。 xxx=$(ls /opt/files/no.such.file) 将产生一个空字符串。
    • [ /opt/files/conf.* -eq "/opt/files/conf.json" ] 仅当仅存在该文件时才会为真。 (不过,当通配符匹配多个文件时,会出现难看的语法错误。)
    猜你喜欢
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    • 2017-12-05
    • 2019-05-23
    • 2021-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多