Bosse_B
Posts: 990
Joined: Thu Jan 30, 2014 9:53 am

Re: Scripting woes, cannot parse inut values properly..

Thu Apr 16, 2020 5:25 pm

Paeryn wrote:
Thu Apr 16, 2020 5:03 pm
Bosse_B wrote:
Thu Apr 16, 2020 9:52 am
The last argument to the getopts call is optional and if missing getopts reverts to use the full command line arguments as given by $@.
But this seems not to work inside a function,
...
Seems like if inside a function it is unable to get the input arguments from the command line!
But reading these into a variable in mainline code and add that variable at the end of the call to getopts makes it work!
The reason that $@ doesn't work for you when used in a function is because inside a function the positional variables $0 to $9, $@ and $# refer to the function's arguments rather than the script's.
So functions can take arguments in this scripting system? None of the tutorials I have found show examples of that. In that case I should really send the $@ as an argument to my function...
I will have to search for such examples now. Arguments to functions is what I use in all other languages instead of using globals (ouch!)...
Bo Berglund
Sweden

jbudd
Posts: 1427
Joined: Mon Dec 16, 2013 10:23 am

Re: Scripting woes, cannot parse inut values properly..

Thu Apr 16, 2020 5:35 pm

Mostly "$VAR" is the same thing as ${VAR} and even "${VAR}" It all gets much more tricky when $VAR is an array.
There are circumstances where you need every quote and bracket you can think of: arrayName2=("${arrayName1[@]}")
In cases like that I try and find an alternative, less cryptic approach!

epoch1970
Posts: 5143
Joined: Thu May 05, 2016 9:33 am
Location: Paris, France

Re: Scripting woes, cannot parse inut values properly..

Thu Apr 16, 2020 5:35 pm

Code: Select all

$ msg(){ echo "Received: $1"; }; for str in "foo" "bar" "baz"; do msg "$str"; done;
Received: foo
Received: bar
Received: baz
"S'il n'y a pas de solution, c'est qu'il n'y a pas de problème." Les Shadoks, J. Rouxel

User avatar
Paeryn
Posts: 2972
Joined: Wed Nov 23, 2011 1:10 am
Location: Sheffield, England

Re: Scripting woes, cannot parse inut values properly..

Thu Apr 16, 2020 7:04 pm

Bosse_B wrote:
Thu Apr 16, 2020 5:25 pm
So functions can take arguments in this scripting system? None of the tutorials I have found show examples of that. In that case I should really send the $@ as an argument to my function...
I will have to search for such examples now. Arguments to functions is what I use in all other languages instead of using globals (ouch!)...
Function parameters are used in exactly the same way as script's parameters, just as if the function was actually a separate script. Everything you can do with a script's parameter list outside of a function works on a function's parameter list when in a function.
She who travels light — forgot something.

Return to “General discussion”