代码之家  ›  专栏  ›  技术社区  ›  Dongho Han

在bash中,我如何比较文件名而不获得拒绝权限的消息?

  •  0
  • Dongho Han  · 技术社区  · 7 年前

    然后删除具有特殊名称的文件

    这是我的密码

    for filename in $1*;do
        if("$filename" == "hello.txt");then
                echo "WOW!"
        fi
        done
    

    我的测试目录是test/并且有两个文件。一个名字是“hello.txt”和“world.txt”;然而,当我运行收到的代码时

    noStrange.sh: line 2: TEST/hello.txt: Permission denied
    noStrange.sh: line 2: TEST/world.txt: Permission denied
    

    chmod u+x scriptname ,它不起作用

    这是我输入的

    sh scriptname TEST/
    

    谁能告诉我剧本有什么问题吗?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Avinash Raj    7 年前

    使用 basename

    for filename in $1*;do if [[ $(basename "$filename") == "hello.txt" ]] ; then echo "wow";fi;    done
    

    使用find命令。这将搜索当前文件夹及其子文件夹中存在的所有文件。

    find . -name 'hello.txt'
    
        2
  •  1
  •   Jordan Samuels    7 年前

    直接的答案是你的测试语法是错误的;你应该有

    if ["$filename" == "hello.txt"]; then

    $filename 将匹配 TEST/hello.txt 而不是 hello.txt

    rm TEST/hello.txt

    如果有要删除的模式,可以使用全局/通配符,或以下组合 find xargs rm . 例如。

    find TEST -name 'hello*.txt' | xargs rm