My latest posts can be found here:
Previous blog posts:
Additionally, some earlier writings:
I mentioned when talking about an oddity in vim that the behaviour
of the command "<n>J" didn't match my mental model. Sometimes
software does that, it had behaviour that's totally reasonable
when you think about it one way, but there's another way of
thinking that causes you to be surprised.
In shell scripting in *nix we can write a script that takes a collection of parameters. Sometimes the script will deal with them one at a time, and can loop over them.
On the other hand, sometimes we want to deal with the first, and iterate until we are done.
The shift command deletes parameter $1 and shifts each of the remaining parameters down by one.
So far so reasonable.
If there are a lot, or we need it to vary, we can put that in a loop, like this:
All that does is execute the shift command $n times. So if you want 10 shifts (which does, admittedly, seem a touch excessive) you can do this:
Checking the man page for shift we see that there's a short-cut for this, because shift takes a parameter to say how many arguments to shift by:
Well, they aren't.
Here are two scripts:
OK, so they both shift out the first three parameters and print the fourth one, printing "Resulting first parameter: 4".
No surprise ... let's try again:
OK, so a more careful reading of the man shift page explains why this is so. The definition of shift <n> is not the same as executing shift "n" times. It mostly is, but in fact, it isn't.
So there we are, another of my mental models out the window.
Send us a comment ...
Links on this page