treed593
treed593

Reputation: 3

Multiple variables from text file in BASH

I am writing a script to RSH into servers from a text file and create a specific user on each system. I work for a university that is currently testing Amazon EC2 for their courses. Is it possible to take colon or comma separated values in a text file like this :

    server.edu:user123:John:[email protected]

and pass them to a BASH script as $server $username etc...

Upvotes: 0

Views: 1175

Answers (2)

user1019830
user1019830

Reputation:

It is possible to read lines of colon-separated data from file into an array directly and index into it:

while IFS=: read -a userdata; do
    printf "server: %s\n"   "${userdata[0]}"
    printf "username: %s\n" "${userdata[1]}"
    printf "name: %s\n"     "${userdata[2]}"
    printf "email: %s\n"    "${userdata[3]}"
done < data_file

Upvotes: 0

anubhava
anubhava

Reputation: 785481

Yes you can use it like this:

> s='server.edu:user123:John:[email protected]'
> IFS=: read server username email <<< "$s"

> echo "$server"
server.edu
> echo "$username"
user123
> echo "$email"
John:[email protected]

EDIT:: For reading this data from file line by line

while IFS=: read server username email; do
   echo "$server"
   echo "$username"
   echo "$email"
done < file

Upvotes: 1

Related Questions