简体   繁体   English

如何在bash shell中的部分中打印passwd的最后一行

[英]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. 我对bash shell脚本非常陌生,我的任务是希望我阅读linux安装副本的最后一行(位于admin文件夹中)passwd文件,该文件包含用户名,真实名称,主目录和登录外壳。 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. 我已经尝试了read命令,但是它将继续输出整个文件,而不只是最后一行,即使如此,我也需要能够分节输出,例如: echo $Username将输出Admin或echo $Realname wold ouptut the用户真实姓名。 I have also tried sed but I get a "cant read, no such file or directory error" 我也尝试过sed,但得到“无法读取,没有此类文件或目录错误”

Edit: After receiving an email from my professor, I DO have to use the read command to get the information from the passwd file. 编辑:收到教授的电子邮件后,我必须使用read命令从passwd文件中获取信息。 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: 这是我编写的返回整个passwd文件的代码:

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!) 分配似乎没有提到使用“ read”命令,因此,如果没有完全给出解决方案,我建议您使用重定向方法(尝试在Unix重定向上进行Google搜索,这很有趣!)

I would also suggest searching on standard and error redirection in Unix. 我还建议在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. 您需要使用IFS定义字段分隔符,然后了解主目录所在的列以及登录Shell。

Understanding fields in /etc/passwd ( http://www.cyberciti.biz/faq/understanding-etcpasswd-file-format/ ) 了解/ 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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