简体   繁体   中英

How to print the last line of passwd in sections in bash shell

I am very new to bash shell scripting and I have an assignment that wants me to read the last line of a copy of my linux installations (that is in the admin folder) passwd file which contains the user name, real name, home directory and login shell. I have tried the read command but it continues to output the entire file rather than just the last line and even so I need to be able to output in in sections, for example: echo $Username would output Admin or echo $Realname wold ouptut the users real name. I have also tried sed but I get a "cant read, no such file or directory error"

Edit: After receiving an email from my professor, I DO have to use the read command to get the information from the passwd file. However your responses have proved useful in helping me understand what I am doing so far. Thank you!

Here is a link to my list of objectives in this script

and here is the code that I have written that returns the entire passwd file:

file="/home/Admin/passwd"

while read -r f1 f2 f3 f4 f5 f6 f7
do
        echo "Username: $f1, Realname: $f2, Homedir: $f3, loginshell: $f4 "
done < "$file"

any help would be greatly appreciated, somehow I feel like I'm reading too much into the instructions but I would like some other opinions, thank you!

Welcome to the wonderful world of scripting!

Assignment does not seem to mention to use 'read' command, so, not giving out the solution completely, I would suggest you use redirection methods (try a Google search on Unix redirection, it is quite fun!)

I would also suggest searching on standard and error redirection in Unix. There are some nifty shortcuts quite easy to find.

Hope this helps!

you need use IFS to define the field separator, then understand what column is home directory, and login shell.

Understanding fields in /etc/passwd ( http://www.cyberciti.biz/faq/understanding-etcpasswd-file-format/ )

Here is the fix:

file="/home/Admin/passwd"

while IFS=: read -r f1 f2 f3 f4 f5 f6 f7
do
   echo "Username: $f1, Realname: $f5, Homedir: $f6, loginshell: $f7 "
done  < "$file"

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