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
}

シェルスクリプトから取得した変数を使用して awk スクリプトに入れて、特定のユーザーの passwd ファイルを検索し、その情報を表示する必要がありますが、それがどのように機能するかはわかりません。-v コマンドの使用方法と awk スクリプトのどこに配置するかが完全にはわかりません。

4

3 に答える 3

0

あなたのスクリプトはほぼ正しいです。シェル コマンドを次のように変更します。

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

そして、awkスクリプトで:

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

使用する方が正確であるという理由$1 == usernameよりも優れて$1 ~ usernameいます。たとえば、と、、のような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 に答える