tags:

views:

32

answers:

3
$ cat fav
#!/bin/bash
for i in {1..7}
do
    echo http://api.stackoverflow.com/1.0/users/113124/favorites?page=$i&pagesize=100 
done
$ ./fav
http://api.stackoverflow.com/1.0/users/113124/favorites?page=1
http://api.stackoverflow.com/1.0/users/113124/favorites?page=3
http://api.stackoverflow.com/1.0/users/113124/favorites?page=6
http://api.stackoverflow.com/1.0/users/113124/favorites?page=5
http://api.stackoverflow.com/1.0/users/113124/favorites?page=7
http://api.stackoverflow.com/1.0/users/113124/favorites?page=4
http://api.stackoverflow.com/1.0/users/113124/favorites?page=2
$
  • Why don't I get &pagesize=100 at the end?
  • Also, why are the results out of order?
+4  A: 

& runs a program in the background, and it's also an "end of command" indicator just like ;, which is why your command is cut short. You can escape it with \ or put the whole thing in double quotes:

echo http://api.stackoverflow.com/1.0/users/113124/favorites?page=$i\&pagesize=100
echo "http://api.stackoverflow.com/1.0/users/113124/favorites?page=$i&pagesize=100"

Interestingly, pagesize=100 was also being executed as a separate command, but that is actually a valid variable assignment. So it wasn't generating an error message which might have clued you in to what was happening.

The backgrounding means all of the echo statements were executed in parallel. That explains why they ended up being executed in random order since the seven processes will finish in an indeterministic order based on when they get time slices from the kernel.

John Kugelman
@John: I did not understand the parallel part. Even though they are executed in background, `i=1` statement is executed before `i=2` statement, isn't it?
Lazer
They are *started* in that order but, because they are being run asynchronously, there is no guarantee in which order they end up executing the `echo` commnands or finishing.
Ned Deily
+1  A: 

Enclose the echo argument in quotes:

echo "http://api.stackoverflow.com/1.0/users/113124/favorites?page=$i&pagesize=100"

& is a shell meta char to run the command in back ground. Enclosing the argument in " make & lose its special meaning.

codaddict
+1  A: 

The & letter is a keyword for the shell. It stands for backgrounding. Use "" around your http string to make your skript behave right.

And read about backgrounding in your shell manual, it is key functionality.

ypnos