Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use Internal Field Separator correctly?

I am trying to set the IFS to ‘:’, but it seems to not work. Here is my code,

FILE="/etc/passwd"

while IFS=':' read -r line; do
        set $line
        echo $1
done < $FILE

When I run my code, it seems to give me the entire line. I have used the set command to assign positional parameters, to extract only the username, but it output the entire line when I try to print the first positional argument $1. What am I doing wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  • IFS=':' read -r line reads the complete line
  • IFS=':' read -r name remainder puts the first field in the variable name and the rest of the line in remainder
  • IFS=':' read -r name password remainder puts the first field in the variable name, the second field in the variable password and the rest of the line in remainder.
  • etc…

In bash you can use read -a array_var for getting an array containing all the fields, and that’s probably the easiest solution for your purpose:

#!/bin/bash

while IFS=':' read -r -a fields
do
    echo "${fields[0]}"
done < /etc/passwd
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading