programiss
programiss

Reputation: 255

Bash script to read variable from text file

I would like to have the following in a text file

name=missy [email protected]

Is it possible to read that into a text file and be able to call the variables $name and $email

Or what is the best way of doing this?

Thank you for all the help

Upvotes: 0

Views: 362

Answers (1)

Doug
Doug

Reputation: 3863

Sure, this is the first way that comes to mind:

#!bash
# set for loop separator to newline
IFS=$'\n'
# loop through each line in the file
for userline in $(cat email_list.txt); do
    # Cut delimiter is a space for the next two lines
    # echo the line into cut, grab the first field as the user
    user=$(echo "$userline" | cut -d' ' -f1)
    # echo the line into cut, grab the second field as the email
    email=$(echo "$userline" | cut -d' ' -f2)

    # Set the delimiter an =, grab field 2
    user=$(echo "$user" | cut -d'=' -f2)
    # Set the delimiter an =, grab field 2
    email=$(echo "$email" | cut -d'=' -f2)

    echo "Username: ${user}, email address: ${email}"
done

email_list.txt:

name=missy [email protected]
name=joe [email protected]

Output:

Username: missy, email address: [email protected]
Username: joe, email address: [email protected]

Upvotes: 1

Related Questions