user3170886
user3170886

Reputation: 21

BASH script: Reading from 1-line file into multiple global variables

I have been struggling in bash to parse and read a parameter file into multiple gobal variables. We run both HPUX and Linux environments, and I'm trying to get this working in BASH. It is currently giving me error on the sed statement. Even when I take out the sed, inside the loop it reads the variable(s), but it the values revert to the global definition as soon as I'm out of the loop. Have tried adding "#!/bin/sh" at top of file, but that doesn't work like borne shell, the commented code is borne shell from the HPUX system. Any help would be appreciated!

set -xv

ReadStat() {
set -xv

while read EngName AllTabs Distribs DropDist BlockSet BlockExp BlockBy MaxProcs ; do
   echo "read: EngName=$EngName AllTabs=$AllTabs Distribs=$Distribs DropDist=$DropDist BlockSet=$BlockSet BlockExp=$BlockExp BlockBy=$BlockBy MaxProcs=$MaxProcs "
done < sed -e "s/||/|-|/g" -e "s/||/|-|/g" -e "s/||/|-|/g" -e "s/|/ /g" $StatFile 

#cat $StatFile |\
#  sed -e "s/||/|-|/g" -e "s/||/|-|/g" -e "s/||/|-|/g" |\
#  sed -e "s/|/ /g" |\
#  read EngName AllTabs Distribs DropDist BlockSet BlockExp BlockBy MaxProcs

}

# main() {


BaseNameIs=`basename $0 '.sh'`

StatFile=/tmp/kz.stat

EngName="it1xxx"
CronJob='Y'
Distribs='B'
DropDist='N'
AllTabs='N'
BlockSet='N'
# BlockExp=`date '+%Y%m%d%H%M'`
BlockExp=`date '+%Y%m%d'`'0000'
BlockBy='none'
MaxProcs=30

MyHost=`hostname`

ReadStat 

# main() }

Input file looks like:

it1xxx|Y|B|N|Y|201401071110|none|30|

Upvotes: 2

Views: 1034

Answers (2)

glenn jackman
glenn jackman

Reputation: 247022

The bash read command can handle this:

vars="EngName AllTabs Distribs DropDist BlockSet BlockExp BlockBy MaxProcs"
IFS='|' read -r $vars dummy < kz.stat
for var in $vars; do echo "$var = ${!var}"; done
EngName = it1xxx
AllTabs = Y
Distribs = B
DropDist = N
BlockSet = Y
BlockExp = 201401071110
BlockBy = none
MaxProcs = 30

It's crucial to not quote $vars in both the read and for commands.

Upvotes: 5

Brad Lanam
Brad Lanam

Reputation: 5733

The problem is that while loops generally run in their own sub-shell. Probably the most straightforward solution is to save the output into a temporary file and then source the temporary file.

Here's a web page that illustrates some solutions. fvue.nl wiki page

Upvotes: 2

Related Questions