1

I am trying to solve an issue which is i need to pass user input to here document and loop its value. I am able to only one thing at time, either pass variable or loop. Both are not working.

Below is my code.

bash <<START
echo "Input :$1"
for i in 1 2 3 4 5
do
echo "For Loop Value : $i"
done
START

While running this script ./heredoc "asd" im am getting below output

Input :asd
For Loop Value :
For Loop Value :
For Loop Value :
For Loop Value :
For Loop Value :

As you can see the value of i is not coming.

But if i add single quote it gives below output.

Input :
For Loop Value :1
For Loop Value :2
For Loop Value :3
For Loop Value :4
For Loop Value :5

How can i solve it so that my input value as well as loop value should come in output.

Thanks in advance

fedorqui
  • 275,237
  • 103
  • 548
  • 598
vinay
  • 1,004
  • 1
  • 11
  • 27

1 Answers1

2

You're not passing anything. $1 will be the first positional parameter of the running shell, probably an empty string.

This will do what you want:

variable="hello there"

bash <<SCRIPT_END
echo "Input: $variable"
for i in 1 2 3 4 5; do
    echo "For Loop Value: \$i"
done
SCRIPT_END

You will have to escape the $i in the here-document as it would otherwise be interpolated with the value of any variable i in the current environment (an empty string if unset).

Note that you do want this to happen for $variable (what you call "passing to the here-document") and that's why we can't just single-quote the whole thing (by changing the first SCRIPT_END to 'SCRIPT_END').

Kusalananda
  • 14,885
  • 3
  • 41
  • 52