【问题标题】:Unix if condition error inside for loopUnix if 循环内的条件错误
【发布时间】:2014-01-25 03:40:00
【问题描述】:
#!/bin/bash

echo "Enter the search string"
read str

for i in `ls -ltr | grep $str  > filter123.txt ; awk '{ print $9 }' filter123.txt` ; do

if [ $i != "username_list.txt" || $i != "user_list.txt" ] ; then

else
 rm $i
fi
done

我是 unix shell 脚本的初学者,我使用 grep 方法根据给定的字符串创建上述文件以删除文件。当我执行上面的脚本文件时,它显示错误,如“./rm_file.txt: line 10: syntax error near unexpected token `else'”。请提出这个脚本中的错误。

【问题讨论】:

  • 你为什么使用grepawk和一个临时文件?只需执行ls -ltr | awk "/$str/{print \$9}" (如果 str 包含某些字符,这将失败,但 grep $str 也是如此)
  • 使用[[]](见mywiki.wooledge.org/BashPitfalls#A.5B_.24foo_.3D_.22bar.22_.5D)。也不知道你为什么要尝试if !a || !b then nothing else something,而不是逻辑上等效的if a && b then something

标签: bash unix


【解决方案1】:

你的代码有几个问题:

  1. Don't parse the output of ls。虽然它可能在大部分时间都有效,但它会因某些文件名而中断,并且有更安全的替代方案。

  2. 用另一个管道替换filter123.txt

  3. 你可以否定条件的退出状态,这样你就不需要else子句了。

  4. 您的if 条件始终为真,因为任何文件名都不等于两个选项之一。您的意思可能是使用&&

  5. ||&&[ ... ] 中不可用。要么使用两个[ ... ] 命令,要么使用[[ ... ]]

解决上述项目:

for i in *$str*; do
    if [[ $i != username_list.txt && $i = user_list.txt ]]; then
        rm "$i"
    fi
done

【讨论】:

    【解决方案2】:

    要对[ 使用布尔运算符,您可以使用以下之一:

    if [ "$i" != username_list.txt ] && [ "$i" != user_list.txt ] ; then ...
    if [ "$i" != username_list.txt -a "$i" != user_list.txt; then ...
    

    但在这种情况下,使用 case 语句可能更简洁:

    case "$i" in
    username_list.txt|user_list.txt) : ;;
    *) rm "$i";;
    esac
    

    【讨论】:

      【解决方案3】:

      thenelse之间什么都没有,如果你不想做什么,你可以把:放在那里

      要删除当前director中名称中带有特定字符串的文件,可以使用find

      #!/bin/bash
      read -p "Enter the search string: " str
      
      # to exclude "username_list.txt" and "user_list.txt"
      find . -maxdepth 1 -type f -name "*$str*" -a -not \( -name "username_list.txt" -o -name "user_list.txt" \) | xargs -I'{}' ls {}
      

      【讨论】:

        【解决方案4】:

        也可以使用find:

        find . -maxdepth 1 -type f -name "*$str*" ! -name username_list.txt ! -name user_list.txt -exec rm {} \;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-10-01
          • 2014-06-26
          • 2017-01-11
          • 2015-08-24
          • 2012-08-18
          • 1970-01-01
          相关资源
          最近更新 更多