开发者

Whats wrong with this bash script?

开发者 https://www.devze.com 2023-01-16 13:00 出处:网络
开发者_Python百科$ cat fav #!/bin/bash for i in {1..7} do echo http://api.stackoverflow.com/1.0/users/113124/favorites?page=$i&pagesize=100
开发者_Python百科
$ 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?


& 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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消