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'

ambikanair
  • 4,004
  • 11
  • 43
  • 83
  • 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?! – Marty McGowan Apr 20 '15 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 – Marty McGowan Apr 20 '15 at 16:57

2 Answers2

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
Moldova
  • 1,641
  • 10
  • 13
0

here is the "foreach" function:

function foreach
{ 
    typeset cmd=$1;
    shift;
    for arg in "$@";
    do
        $cmd $arg;
    done
}
Marty McGowan
  • 356
  • 2
  • 10
  • What's the point of quoting `"$@"` if you aren't going to quote `$arg`? – Charles Duffy Apr 20 '15 at 17:04
  • 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). – Charles Duffy Apr 20 '15 at 17:07
  • Also, why the `function` keyword? That breaks POSIX sh compatibility... and to what end? – Charles Duffy Apr 20 '15 at 17:08