【问题标题】:How to compare file names in SHELL SCRIPT如何在 SHELL SCRIPT 中比较文件名
【发布时间】:2021-10-31 14:43:38
【问题描述】:

我有两个文件名

file1 = "my_random_forest_2021-08-11-094538.csv.zip"
file2 = "my_random_forest_2021-08-11-094538.csv.zip"

if [$file1 == $file2]; then
    echo "matched"

在执行脚本时它说:

test.sh: line 5: [my_random_forest_2021-08-11-094538.csv.zip: command not found

如何比较上述格式自带的文件名?

【问题讨论】:

  • 如果这真的是 POSIX shell,你也(除了缺少空格)需要使用= 作为操作符,而不是==。详见man test

标签: python shell unix


【解决方案1】:

正确的语法应该是这样的

file1="my_random_forest_2021-08-11-094538.csv.zip"
file2="my_random_forest_2021-08-11-094538.csv.zip"
if [ $file1 = $file2 ] 
then
    echo "matched"
fi

声明变量时没有空格。
变量和方括号之间应该有 whilespace。
; 在 if 之后不需要。如果要添加 if 然后在一行中添加;
匹配将使用= 而非== 完成。
if 应以fi 结束以关闭语句。

【讨论】:

    【解决方案2】:
    if [ "$file1" = "$file2" ]; then
    echo "matched";
    fi
    

    您在方括号和变量名之间缺少一个空格。如果没有空格,shell 会将“[my_random_forest_2021-08-11-094538.csv.zip”解释为命令(不存在)。

    【讨论】:

    • @JamesSchultz:不应该是[ "$file1" = $file2" ]吗?至少根据man test,你的版本是不允许的。
    • 你说得对,我已经相应地更新了答案。它在 bash 和 zsh 中工作,所以尽管没有记录,所以我没有注意到。尽管它确实有所作为,但它在 sh 中失败了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    • 2014-05-22
    • 2014-04-08
    • 1970-01-01
    相关资源
    最近更新 更多