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

5
  • tried bash <<'START' but in that case i am loosing my user input variable value as mentioned in post..Thanks anyway. Commented Jun 21, 2016 at 13:25
  • 2
    Oh, sorry! then escape the expansions: echo "For Loop Value : \$i" Commented Jun 21, 2016 at 13:27
  • "gniourf_gniourf" you are genius..thanks..that worked... Commented Jun 21, 2016 at 13:29
  • 1
    Now the real question is why are you using a heredoc like so in the first place? Commented Jun 21, 2016 at 13:30
  • Here is the real question. "sudo -u vinay bash <<EOF echo "Input value after SUDO $1" IFS=';' read -ra ADDR <<<"$1" for i in "${ADDR[@]}"; do echo "\$i" done echo "end" EOF " it should print input value. so if i give input "asd;qwe;zxc" it should print asd qwe zxc But its not printing:(. Commented Jun 21, 2016 at 13:38

1 Answer 1

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').

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.