i am newbie in bash-scripting and linux. I want to write a script to get a username from the terminal and say whether that username is on the passwd or not. i wrote and tried below script but it doesn’t work. help me that what i can do.
users = cat /etc/passwd echo User_Name cat users | grep User_Name if [ User_Name in users ]; then echo "User_Name FOUND" else echo "User NOT FOUND!" fi
how i can define a variable to read a string from termnial.
Advertisement
Answer
To print and read an argument from terminal, you should use echo and then use read commane and then call it with dollar-sign, finally the script know what you want. for example:
echo "Enter UserName: " read User_Name
here is the correct form of your code:
echo "Enter the Username: " read User_Name cut -f 1 -d: /etc/passwd | grep -q $User_Name if [ $? -eq 0 ]; then echo "User $User_Name FOUND" else echo "User NOT FOUND!" fi
Tips:
cut -f 1 -d #cut the first column of the passwd list grep -q # find username and do not write anything to standard output in terminal. if [ $? -eq 0 ] #in linux terminal when we want to know whether the previous command is executed correctly we use $? and the output must be 0. and - eq means equal to 0. and when we use that, it means if previos command (grep the username) executed correctly and the username was found, then run next step and print it found.