0

in order to parse the arguments list I tried to implement a common top-down parsing scheme.

I wondered why my eat() function wouldn't work. Because the positional arguments $1, $2, $3, ... are in the context of that particular function. Not the ones of the actual script. Bummer. I'm didn't yet grow accustomed to bash.

So my question is, if it is therefore correct, that also the scope of shift is the context of my eat() function, yes?

Is there really no way of shifting the script arguments from inside another function? : (

[That means I have to implement ALL logic (that normally adheres to a top down parsers') in a case statement ! (!?)]

von spotz
  • 435

1 Answers1

3

A function can return all (or a subset) of the arguments it was passed (e.g. via a global array), and the calling script can then use that to set its own args. e.g.

#!/bin/bash

declare -a args

nofoo() {

we don't like "--foo", it is forbidden!

for a in "$@"; do [ "$a" != "--foo" ] && args+=("$a") done }

nofoo "$@" set -- "${args[@]}"

From help set in bash:

set: set [-abefhkmnptuvxBCHP] [-o option-name] [--] [arg ...]

Set or unset values of shell options and positional parameters.

Change the value of shell attributes and positional parameters, or display the names and values of shell variables.

[...]

-- Assign any remaining arguments to the positional parameters. If there are no remaining arguments, the positional parameters are unset.

cas
  • 78,579
  • 1
    This would unfortunately break on arguments containing characters in $IFS (space, tab, newline), as well as arguments containing filename globbing characters. – Kusalananda Jun 03 '21 at 07:05
  • @Kusalananda In that case use a global array instead of trying to return the arg subset with printf. This was only meant to be a very simple and silly example to demonstrate in principle how to modify an argument list from within a function, it was not meant to be perfect. – cas Jun 03 '21 at 07:21
  • It looks better now. – Kusalananda Jun 03 '21 at 07:29