1
#!/bin/bash
# This tells you that the script must be run by root.
if [ "$(id -u)" != "0" ];
  then
echo "This script must be run as root!" 1>&2
exit 1
fi

userexists=0
while [ $userexists -eq 0 ]
do
# This asks for the user's input for a username.
  echo -n "Enter a username: "
  read username

  x="$username:x:"
# This if block checks if the username exists.
  grep -i $x /etc/passwd > /dev/null
  if [ $? -eq 0 ]
    then
      userexists=1
    else
      echo "That user does not exist!"
  fi
done
# This is the heading for the information to be displayed
echo "Information for" $username
echo "--------------------------------------------------------------------"


awk -v varname="var" -f passwd.awk /etc/passwd
awk -f shadow.awk /etc/shadow







BEGIN { FS = ":" }


/"variable"/{print "Username\t\t\t" $1
print "Password\t\t\tSet in /etc/shadow"
print "User ID\t\t\t\t"$3
print "Group ID\t\t\t"$4
print "Full Name\t\t\t"$5
print "Home Directory\t\t\t"$6
print "Shell\t\t\t\t"$7
}

我需要使用从 shell 脚本中获得的变量并将其放入 awk 脚本中以搜索特定用户的 passwd 文件并显示所述信息,但不确定它是如何工作的。我不完全了解如何使用 -v 命令以及将其放在 awk 脚本中的什么位置。

4

3 回答 3

1

如果您需要做的就是将shell变量作为awk变量$username传递:awkvarname

awk -v varname="$username" -f passwd.awk /etc/passwd

然后,在您的awk程序中,您可以引用varname( without $ ),它将返回与shell上下文$username中相同的值。

由于/etc/passwdis :-separated 并且用户名是第一个字段,因此您可以通过以下方式专门匹配用户名字段:

awk -F: -v varname="$username" -f passwd.awk /etc/passwd

然后,在内部passwd.awk,您可以使用以下模式:

$1 == varname 
于 2014-05-11T20:05:49.943 回答
0

您的脚本几乎是正确的。将 shell 命令更改为:

awk -v username="$username" -f passwd.awk /etc/passwd

然后在awk脚本中:

$1 == username { print "Username\t\t\t" $1
...
}

使用$1 == username更好,$1 ~ username因为它更准确。例如,如果, 并且您在like , ,username=john中有其他相似的用户名,它们都会匹配。使用将是严格匹配的。/etc/passwdjohnsonjohnnyeltonjohn$1 == username

另外,这不是很好:

grep -i $x /etc/passwd

-i标志使其成为不区分大小写的匹配,但 UNIX 中的用户名区分大小写(john并且John不是一回事)。只需放下-i旗帜以更准确。

最后,脚本的第一部分可以更短更清晰:

#!/bin/bash
# This tells you that the script must be run by root.
if [ $(id -u) != 0 ]; then
    echo "This script must be run as root!" >&2
    exit 1
fi

while :; do
    # This asks for the user's input for a username.
    echo -n "Enter a username: "
    read username

    # This if block checks if the username exists.
    if grep ^$username:x: /etc/passwd > /dev/null; then
        break
    else
        echo "That user does not exist!"
    fi
done

基本上我去掉了不必要的元素、引用和简化的表达方式,并且grep更加严格,并且稍微清理了格式。

于 2014-05-11T20:30:43.877 回答
0

仅关于 awk 部分:您可以简单地在执行部分中使用变量。

例子:awk -v varname="var" -v user="David" '$1==user {print varname;}"'

于 2014-05-11T19:34:20.577 回答