【问题标题】:Bash Script to validate the existence of User Name in /etc/passwd用于验证 /etc/passwd 中是否存在用户名的 Bash 脚本
【发布时间】:2012-06-21 14:52:36
【问题描述】:

我想创建一个 Bash 脚本来检查 /etc/passwd 中是否存在用户名。如果存在则将其添加到users.txt 文件中。

我不太擅长 UNIX 编程,所以希望有人能帮助我。

while(get to the end of /etc/passwd){

  name=$(cat /etc/passwd | cut -d: -f1);
  num1=$(cat /etc/passwd | cut -d: -f3);
  num2=$(cat /etc/passwd | cut -d: -f4);

  if(num1==num2)
   /*i compare argv[0] with $name */
   /* if true i=1 */

}

if(i==1)
  save following string "argv[0]=agrv[1]"
else
  "error message"

【问题讨论】:

    标签: bash unix cat


    【解决方案1】:
    #!/bin/bash
    read -p "Username: " username
    egrep -q "^$username:" /etc/passwd && echo $username >> users.txt
    

    注意:如果您只是想测试用户名是否存在,最好只使用id

    if id -u $username >/dev/null 2>&1;
    then
        echo $username >> users.txt
    fi
    

    > /dev/null 2>&1 仅用于停止打印id 的输出(即$usernameuid,如果它存在,或者如果用户不存在错误消息)。

    【讨论】:

      【解决方案2】:
      #!/bin/bash
      
      found=false
      
      while IFS=: read -r name _ num1 num2 _
      do
          if (( num1 == num2 ))
          then
              if [[ $name == $1 ]]
              then
                  printf '%s\n' "$1=$2"
                  found=true
              fi
          fi
      done < /etc/passwd > users.txt
      
      if ! found
      then
          printf '%s\n' "error message" >&2
          if [[ -e users.txt && ! -s users.txt ]]
          then
              rm users.txt
          fi
      fi
      

      【讨论】:

        【解决方案3】:
        #!/bin/bash   
        read -p "Enter a username: " username
        getUser=$(cat /etc/passwd | grep $username | cut -d":" -f1)
        echo $getUser >> users.txt
        

        实际上不需要循环,就好像它不存在一样,它不会向文件中添加任何内容。

        【讨论】:

        • 无用的猫:grep $username /etc/passwd.
        • 另外:您将匹配行中的任何位置的$username。您需要确保您只有 grep 的用户名。另外,如果不匹配,您只需将空行输出到users.txt
        • 无论如何这是一个好的开始,但也有一些问题,如前所述
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-18
        相关资源
        最近更新 更多