Bash Script input variables from file

Whether you are using Linux on the desktop or as a server, it's still good that you're using Linux. Linux related questions go here.

Moderator: General Moderators

Post Reply
facets
Forum Contributor
Posts: 273
Joined: Wed Apr 13, 2005 1:53 am
Location: Detroit

Bash Script input variables from file

Post by facets »

Hi All,

How would I assign variables in a bash script from a text file with 2 strings per line separated by a : ?
This code is echoing the code back, but I have no idea how to assign the variables.

Code: Select all

#!/bin/bash
while read a ; do
echo $a
done < file.list
Any pointers would be rad!

Will./
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

what variables are you trying to assign? what's in the file you're reading?
facets
Forum Contributor
Posts: 273
Joined: Wed Apr 13, 2005 1:53 am
Location: Detroit

Post by facets »

currently just inputting text.
the test file looks like this.
  • One,Two
    Three,Four
    Five,Six
So I wish to (eventually) loop through these items so

Loop1 >
Var1 = One
Var2 = Two

Loop2 >
Var1 = Three
Var2 = Four

etc..
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Use awk with a "," field separator to split each line, then get your variables from there ;)
facets
Forum Contributor
Posts: 273
Joined: Wed Apr 13, 2005 1:53 am
Location: Detroit

Post by facets »

Here's what I ended up with.. Thanks all for help.
If someone wants to help me with an awk one liner.. be my guest :)

Code: Select all

#!/bin/bash
while IFS=" " read name pass
do
useradd "$name" -p "$pass"
done < mkuser.txt
exit 0
tks, Will./
User avatar
ibbo
Forum Commoner
Posts: 51
Joined: Tue Sep 19, 2006 6:20 am

Post by ibbo »

you can assign from file via awk like this

NAME=`awk -F, '{print $1}' /path/to/data`
PASS=`awk -F, '{print $2}' /path/to/data`

But this has problems when you have multiple entries in your file. Your method works good enough.

Ibbo
Post Reply