简体   繁体   中英

Passing Bash variables to an awk script

I am trying to get a bash script to use the username I give it. Put the Username as a variable and pass it to my awk script, so I can display the user's info in the manner I put it in my awk script. This is what I have so far.

#!/bin/bash

read -p "Username:" $user 

 awk -v var="$user" -f passwd.awk /etc/passwd

AWK Script

BEGIN { FS = ":" }

if (var == $1){
    print ""
    print "UserName:"$1 
    print "Password Encrytped:"$2
    print "User Number:"$3 
    print "User Group:" $4
    print "FullName:" $5
    print "User Directory:" $6
    print "User Shell:" $7
 }

Instead of :

read -p "Username:" $user

Use:

read -p "Username: " user

You need to provide a variable's name to read not its value.

You need to enclose your awk if statement in a block

BEGIN { FS = ":" }

{
    if (var == $1){
        print ""
        print "UserName:"$1 
        print "Password Encrypted:"$2
        print "User Number:"$3 
        print "User Group:" $4
        print "FullName:" $5
        print "User Directory:" $6
        print "User Shell:" $7
     }
}

You also need anubhava's answer , removing the sigil ( $ ) on the read line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM