Shifting positional parameter inside a function
I need to shift the positional parameters of a script inside a function, but any call to "shift 1" inside a function shifts only the parameters of that function. Is there some way of
accomplishing that? I tried another approach using an alias. The problem is that I have to take the result of the alias. So I call in my script: Code:
var=$(shiftalias) Thanks. |
Maybe a little more detail would be helpful. What exactly are you trying to do?
How are you using the alias? Also you might consider that using shift inside the function is shifting the function's copies of the parameters, not the actual global values. |
I figured out why the call $(shiftalias) doesn't work. The call is executed in a subsheel, so it does not interfere in the script.
But I still need to know some way to change the script parameters inside a function. |
From what I read in the Bash manpage, there is no way (documented) to do this. When in a function, the positional params are replaced with those of the function, if any. `shift` then applies to them. That's apparently the end of story (manpage version anyhow).
However, (assuming the above is correct) is there no possible way to re-write the code so that you can work around this? If the script isn't gigantic, would it maybe help if you posted it so that someone may see and suggest a way to get around the issue? |
Quote:
|
Quote:
|
Before you get into the function call, stick the script's parameters into an array. Once you are inside the function, manually shift the array elements using a loop. Here's an example:
First copy your positional parameters ($1, $2, etc.) into an array called "blah": Code:
blah=( $(echo $*) ) Code:
# code to shift blah[] to the left by one: Maybe there's another way- but this works. |
That's a good solution and exactly what I would have done.
|
Quote:
That would be a good solution, but the problem is I do not want to worry about the function outside it. The function will be used in many scripts and I do not want to have to call any code every time I use the function. |
Hmm.. Well, going with this same idea, my only further suggestion would be to have the array assignment code I put above, plus the function itself which contains the shifting loop, into a single file which gets sourced into any other scripts that need the function. So, when you source the file, automatically blah[] gets assigned the values of $1 $2 etc and the function contains the loop.
I have no other idea - maybe someone else can give a different idea, or you'll just need to do some more working around. :) Good luck with this; keep us posted as to what you come up with for a solution. |
All times are GMT -5. The time now is 12:33 AM. |