bash script read line by line

0

Hello I am trying to create a script that reads my file take all the variable it needs then use it for another command. But it seems that the variables are not being memorized, because I tried a printf instead of running my script and I got an empty output.

here is my code

#!/bin/bash
numparams=$#
params=$*
cat tots.txt | while read;
do  awk '{
regid=$1;
uport=$2;
ongoingcalls=$3;
ingeg=$4;
maxcalls=$5;
if($3<$5) state=0
if($3==$5) state=1
if($3>$5) state=2
}'
/home/send_script.sh -o "$regid $uport $ongoingcalls $ingeg $maxcalls $state"
done

And here is the tots.txt content:

enter image description here

Peter Hayek

Posted 2015-12-11T10:01:31.993

Reputation: 137

And by "the variables are not being memorized", you mean exactly what? – Run CMD – 2015-12-11T10:23:28.837

so for example if afte the awk command I type printf "$regid" it will give me nothing. – Peter Hayek – 2015-12-11T10:24:54.633

Well, awk variables are not bash variables. You would need to assign the result of awk to bash variables. But you don't need awk at all in this case. I'd just use bash features. – Run CMD – 2015-12-11T10:30:14.223

Play around with 1) test aka [] to set state and 2) the following snippet: while read line; do set $line; echo $1 $2 $3 $4; done and you'll get where you want. – Run CMD – 2015-12-11T10:34:11.213

Answers

2

This is because your variables are being set in the subshell you open by saying cat <file> | while .... So when this subshell is done, you cannot access to those variables any more.

Instead, say:

while read; do
    ...
done < tots.txt

Interesting reading: I set variables in a loop that's in a pipeline. Why do they disappear after the loop terminates? Or, why can't I pipe data to read?.

Note also that you seem to have some confusion between awk and shell variables. Whatever you set in awk will remain there, so saying awk '{$var=2}' is two times incorrect: variables in awk are set without the $ ($var will refer to the column number var) and then the var is just in the scope of awk and not available in your shell.

Maybe you want to do something like:

results=($(awk 'BEGIN {print 1,2,3,"a"}'))

So that you create an array results[] that you can later on access.

fedorqui

Posted 2015-12-11T10:01:31.993

Reputation: 1 517