1

I'm creating a script to automate adding users from a text file in Unix using Bash

I've read a file into a script which is being held in $FILE

The file is in the following format: e-mail;birthdate;groups;sharedFolder

I want to ignore the first line in the file and read the data into variables

I have already set the IFS to ';' earlier. Currently I have

sed 1d $FILE | while read EMAIL BIRTH GROUPS SHAREDFOLDER
do
echo "$EMAIL"
done < $FILE

But when I echo out the EMAIL variable, I get nothing

Ali97
  • 91
  • 8

1 Answers1

3

You are attempting to redirect standard input twice. The pipeline and the < can't both be connected to while read. On my Bash the < wins:

bash$ echo moo | cat <<<bar
bar

Apparently you want simply

sed 1d "$FILE" | while read -r EMAIL BIRTH GROUPS SHAREDFOLDER
do
    echo "$EMAIL"
done

though this can meaningfully be reduced to just

sed 1d;s/;.*//' "$FILE"

You also really want to use lower case for your private variables, but that's a separate discussion.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • For some reason, I still get no output from echo, even using your method. If I only add one variable to my read statement, then echo out that variable, it echos out each line. It's almost like the IFS isn't splitting on ";" – Ali97 Aug 22 '19 at 13:16
  • @Ali97 Does `sed '1d;s/;.*//' "$FILE"` outputs anything? – KamilCuk Aug 22 '19 at 13:17
  • Or are you trying to access the variable outside the loop? That won't work in many scenarios; see https://mywiki.wooledge.org/BashFAQ/024 – tripleee Aug 22 '19 at 13:19
  • I'm unsure what the cause of the issue was, but with the EXACT same statement, if I changed my variables to lowercase, it worked perfectly fine. I'll mark this answer as correct as it was the most comprehensive and did make mention about variables being lowercase – Ali97 Aug 22 '19 at 14:07
  • Just seen that there is an environmental variable called "GROUPS". They were probably clashing. I assume this is why private variables should be lowercase – Ali97 Aug 22 '19 at 14:20
  • Yeah, exactly. I'll add a link. – tripleee Aug 22 '19 at 14:30
  • @Ali97 Apparently bash version 4 (and probably 5) treats an attempt to `read` to the `GROUPS` special variable as an error (and `read` getting an error exits the loop). – Gordon Davisson Aug 22 '19 at 15:12