This question already has an answer here:

I have a variable in bash script dirs= "4"; I want to get this number from another file so I am using a command dirs= sed -n '1p' < test.txt; It gets me the number, I see it in the terminal. But Later in the code, I want to use a loop for dir in dirs.. it does not work because in the script it does not understand that dir is number.

d= sed -n '1p' < test.txt
for dirs in $d    
  echo "$dirs"
dirs= read $dirs

speeds= sed -n '2p' < test.txt 

for speeds in $s    
  echo "$speeds"
for dir in $dirs
  for speed in $speeds
    echo "speed=$speed   dir=$dir"

marked as duplicate by G-Man, drewbenn, Prvt_Yadv, DarkHeart, Stephen Harris Apr 11 at 3:21

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.


You need to use: speeds=$(sed -n '2p' < test.txt)

What's actually happening is bash sees that space and treats speeds= and sed... as different commands. So it sets speeds to the empty string and then runs sed (which is why you see the value being printed when you run the script: it's being printed to the terminal instead of being saved to the variable). You need to wrap the sed command in $( ) to get it to run in a subshell and return the output; then remove that space after = to get it assigned to the variable you want.

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