-1

我想创建一个 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"
4

3 回答 3

4
#!/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仅用于停止打印的输出(iduidof $username,如果它存在,或者如果用户不存在则错误消息)。

于 2012-06-21T15:12:39.073 回答
0
#!/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
于 2012-06-21T16:18:14.750 回答
0
#!/bin/bash   
read -p "Enter a username: " username
getUser=$(cat /etc/passwd | grep $username | cut -d":" -f1)
echo $getUser >> users.txt

真的不需要有一个循环,就好像它不存在一样,它不会向文件添加任何内容。

于 2012-06-21T15:07:08.920 回答