views:

52

answers:

1

Say I have a bash script as follows

while
 read $f;
do
 cat $f >> output.txt;
 echo "aaa" >> output.txt;
done

Yet the second echo statement isn't executed. At all. What am I doing wrong?

I'm running this via

tail -f /var/log/somelog | ./script.sh

$f should not be empty. It's only supposed to output when tail notices a change in the file.

+6  A: 

The variable $f is probably empty, and your script is hanging on a call to cat with no arguments. Did you want to say

while read f

instead of

while read $f

?

mobrule
Everything works find until I add the `echo "aaa">>output.txt;` line. I'm piping in a `tail` command. Question updated.
Josh K
As they say, "Binjo!"
Kevin Little
@Kevin, I'm confused.
Josh K
@mobrule: It's not empty, at least it ceases to become empty when something get's written to the file it's tailing. As mentioned this works fine without the second echo.
Josh K
@Josh K: using variables like that is "doing it wrong". Use `while read f`, not `while read $f`. Your code evaluates to: `while read; do cat >> output.txt; ...; done`. Also, always quote variables you use to at least get some error message from `cat` (in this case); i.e. `cat "$f"` with an empty/undefined `$f` would result in `cat: : No such file or directory`.
janmoesen
So remove the `$` from all instances?
Josh K
@Josh: No, when you're setting the value of the variable there's usually no `$`. When you're using the value, you do use `$`. The exception to the first "rule" is when you're using indirection (`x=y; read $x; echo $y` will output the value entered to the read statement (e.g. "4"). If you did `echo $x` it will say "y". To get the value of an indirection: `echo ${!x}` which might output "4". But indirection is not what you want in this case).
Dennis Williamson