0

I have stored some arguments value in sample.txt

1 >> sample.txt
2 >> sample.txt
3 >> sample.txt

I have tried to parse the sample.txt in a shell script file to collect and assign the values to specific variables.

   #!/bin/sh     
   if [ -f sample.txt ]; then

   cat sample.txt | while read Param

   do

   let count++
   if [ "${count}" == 1 ]; then

   Var1=`echo ${Param}`

   elif [ "${count}" == 2 ]; then

   Var2=`echo ${Param}`

   else

   Var3=`echo ${Param}`

   fi

   done

   fi


echo "$Var1"
echo "$Var2"

echo results prints nothing. I would expect 1 and 2 should be printed. Anyone help?

1 Answer 1

2

You are running the while loop in a subshell; use input redirection instead of cat:

while read Param; do
  ...
done < sample.txt

(Also, Var1=$Param is much simpler than Var1=$(echo $Param).)

However, there's no point in use a while loop if you know ahead of time how many variables you are setting; just use the right number of read commands directly.

{ read Var1; read Var2; read Var3; } < sample.txt
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.