Skip to Content
Linux Shell Scripting Cookbook - Third Edition
book

Linux Shell Scripting Cookbook - Third Edition

by Clif Flynt, Sarath Lakshman, Shantanu Tushar
May 2017
Beginner
552 pages
28h 47m
English
Packt Publishing
Content preview from Linux Shell Scripting Cookbook - Third Edition

How to do it...

Let's go through another example usage of IFS to parse the /etc/passwd file. In the /etc/passwd file, every line contains items delimited by :. Each line in the file corresponds to an attribute related to a user.

Consider the input: root:x:0:0:root:/root:/bin/bash. The last entry on each line specifies the default shell for the user.

Print users and their default shells using the IFS hack:

#!/bin/bash 
#Desc: Illustration of IFS 
line="root:x:0:0:root:/root:/bin/bash"  
oldIFS=$IFS; 
IFS=":" 
count=0 
for item in $line; 
do 

     [ $count -eq 0 ]  && user=$item; 
     [ $count -eq 6 ]  && shell=$item; 
    let count++ 
done; 
IFS=$oldIFS 
echo $user's shell is $shell;

The output will be as follows:

root's shell is /bin/bash

Loops are very useful in ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering Linux Shell Scripting - Second Edition

Mastering Linux Shell Scripting - Second Edition

Mokhtar Ebrahim, Andrew Mallett

Publisher Resources

ISBN: 9781785881985