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

  • And by "the variables are not being memorized", you mean exactly what? – Run CMD Dec 11 '15 at 10:23
  • so for example if afte the awk command I type printf "$regid" it will give me nothing. – Peter Hayek Dec 11 '15 at 10:24
  • 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 Dec 11 '15 at 10:30
  • 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 Dec 11 '15 at 10:34
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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.