如何使用临时文件中的 grep 结束循环?

如何使用临时文件中的 grep 结束循环?

我被困住了!

我有一个脚本。我想检查用户是否是系统用户(感谢@pLumo)。

我将非系统用户提取到临时文件中,然后使用 grep 检查变量是否在临时文件中。问题是,当我按 q 时,我无法退出循环,因为 grep 命令在临时文件中找不到用户“q”。

     read -p "Enter the username you want to delete (q to quit) " name

     user=$( cut -d: -f1 /etc/passwd | grep -w "^$name$" ) 2>>/dev/null         
     awk -F: '$3 >= 1000 && $3 <= 60000 && $6 ~ /^\/home/ {print $1}' /etc/passwd >/tmp/testuser

     if [ "$name" != "q" ]
     then        
       until [ $(grep -w "$user" /tmp/testuser) ] && [[ "$name" =~ $regex ]]  && [[ ! -z "$name" ]] && [ "$name" != "q" ]
       do
          read -p "User system or nonexistant, try again (q to quit) " name
          user=$( cut -d: -f1 /etc/passwd | grep -w "^$name$" ) 2>>/dev/null
       done      
          if [ "$name" = "q" ]
          then
            echo "You quit the program"
            exit
          fi
     fi

答案1

第二个if-block 需要包含在until-loop 中。必须在第一个 -command 后添加对输入名称的检查read

     read -p "Enter the username you want to delete (q to quit) " name

     if [ "$name" = "q" ]
     then
       echo "You quit the program"
       exit
     fi

     user=$( cut -d: -f1 /etc/passwd | grep -w "^$name$" ) 2>>/dev/null         
     awk -F: '$3 >= 1000 && $3 <= 60000 && $6 ~ /^\/home/ {print $1}' /etc/passwd >/tmp/testuser

     if [ "$name" != "q" ]
     then        
       until [ $(grep -w "$user" /tmp/testuser) ] && [[ "$name" =~ $regex ]]  && [[ ! -z "$name" ]] && [ "$name" != "q" ]
       do
          read -p "User system or nonexistant, try again (q to quit) " name         
          if [ "$name" = "q" ]
          then
            echo "You quit the program"
            exit
          fi
          user=$( cut -d: -f1 /etc/passwd | grep -w "^$name$" ) 2>>/dev/null
       done
     fi

相关内容