2

I am trying to create a shell script using another script. Following is the code.

#!/bin/bash
count=$#
cat << EOF > /tmp/kill_loop.sh 
#!/bin/bash

while true;
do
    for i in "$@"
    do
       echo $i
    done

done 
EOF

When I see kill_loop.sh , "$i" is empty.

#!/bin/bash
while true;
do
    for i in "one two three"
    do
       echo

    done
done

I want "$i" to be printed as such in kill_loop.sh file so that if i execute kill_loop.sh, it echoes the value 'one','two' and 'three'

2
  • this looks like an exercise in "here"-file syntax. and not a very productive one at that. here's an alternative exercise: write a function "foreach" which executes it's first argument on the remainder. then this whole exercise becomes: "foreach echo one two three" not to mention in the original code, even with correct syntax, the while true; do ... never terminates?! Commented Apr 20, 2015 at 16:52
  • or if this was an exercise in killing a task run in the background, then you don't need a "here"-file to create a 'forever' loop?! conflating two learning points in one exercise is never a useful approach. pardon me if i'm incorrectly assuming this is an exercise Commented Apr 20, 2015 at 16:57

2 Answers 2

3

Your "outer" shell script is interpreting $i as if it were one of its own variables, which isn't set, thus it evaluates to nothing. Try escaping the $ so the outer shell doesn't expand it:

echo \$i
Sign up to request clarification or add additional context in comments.

2 Comments

Or put it in single quotes
Single quotes won't help. The $ is effectively inside double quotes as part of the here document.
0

here is the "foreach" function:

function foreach
{ 
    typeset cmd=$1;
    shift;
    for arg in "$@";
    do
        $cmd $arg;
    done
}

3 Comments

What's the point of quoting "$@" if you aren't going to quote $arg?
Leaving $cmd unquoted is also an interesting decision; depending on the desired semantics around how a cmd that consists of multiple words (or includes shell indirections or expansions) should be treated, it might be correct to quote cmd's expansion; to use read -a to read it into an array and perform a quoted expansion of that array; or to go all the way and use eval (allowing even dangerous shell constructs to be used).
Also, why the function keyword? That breaks POSIX sh compatibility... and to what end?

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.