problem with if statement

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ZS369
    New Member
    • Aug 2018
    • 8

    problem with if statement

    Hi! When one types a user that doesnt exist it immediately goes to the else statement instead of into the if statement and prints user doesnt exist how do i change this? This is my function:

    function viewUserPropert ies {
    echo "Which user would you like to view?"
    read user

    if [[ $user == 0 ]];
    then
    echo "User does not exist!"
    else
    printf "\nUser view for $user\n"
    printf "\n-15s\n %-15s\n %-15s\n %-15s\n
    %-15s\n%-15s\n%-15s\n", "Username" "Password" "User ID" "Group ID" "Directory" "Shell"
    getent passwd $user | tr ':' '\n'

    fi
    }


    Output now:
    view for arnold

    Username
    Password
    User ID
    Group ID
    Directory
    Shell
    arnold
    x
    1003
    1003
    /home/arnold
    /bin/bash

    I also wish to change the output into table format as seen below. How do i do that? Thanks in advance!

    view for arnold

    Username arnold
    Password x
    User ID 1003
    Group ID 1003
    Directory /home/arnold
    Shell /bin/bash
  • Luuk
    Recognized Expert Top Contributor
    • Mar 2012
    • 1043

    #2
    You are not checking if your user exists, or not!
    Also if you do not enter a username, $user will be '', and $user will only be 0 if you type-in '0'.

    I rewrote your code to this:
    Code:
    #!/bin/bash
    #set -x
    read user
    getentUser=$(getent passwd $user)
    if [[ $? != 0 ]];
    then
                    echo "User does not exist!"
    else
                    printf "\nUser view for $user\n"
    
                    (
                    echo "Username:Password:User ID:Group ID:Directory:Shell"
                    echo "$getentUser"
                    ) | gawk -F: 'NR==1{ for (i=1; i<=6; i++) { a[i]=$i }}
                    NR==2{ for (i=1; i<=6; i++) { b[i]=$i }}
                    END{ for (i=1; i<=6; i++){ printf "%-15s: %-15s\n", a[i], b[i]}}'
    fi
    on line#4 the existance if the user is tested
    line#5 if the returnvalue of getent is not equal to 0, than $user does not exist
    lines#11-#13 create the output on 2 lines, with fields separated by ':
    lines#14-#16 use GAWK to display a table

    if you remove the '#' in line#2, you will see every line before it gets evaluated.
    Last edited by Luuk; Jan 1 '19, 12:14 PM. Reason: comment added

    Comment

    Working...