0

I use this function to feed some filenames to another command.

function fun(){  
  find "${@}" -print0 | xargs -r0 other_command
}

When invoked, all arguments a passed to find in order to filter the filenames ( -type, -name, etc.)

Is there some way to pass some of those arguments to other_command ? Variable amount of arguments if possible.

Something like this

fun [list of aguments for find] [list of aguments for other_command]   # pseudo-phantasy syntax

Is it possible?

stander
  • 45
  • 5
  • 1
    In every language allowing to pass variable arguments to a function, there are two common constraints: 1) Variable arguments must be last or after positional arguments. 2) There can be only one set/type of variable arguments. When facing the need for a function to process two or more lists of entries; you usually pass these by reference rather than value. See [Andrej's answer](https://stackoverflow.com/a/69785171/7939871) – Léa Gris Oct 31 '21 at 09:22
  • Yes, that answers my question. I've managed to constrruct a string that includes find and grep, each with their own parameters taken from the 2 array, and ejecute it with eval: cmdLine="find $paramFirst -print0 | xargs -r0 grep $paramSecond" eval $cmdLine But as we know, ````eva```` is insecure and so far I couldn't find a way to make it secure – stander Oct 31 '21 at 20:21
  • I've tried the solution from https://stackoverflow.com/a/52538533/17281195 but it can't work here because "find" is executed inside token_quote. And the pipe character can't be quoted. – stander Oct 31 '21 at 20:32

1 Answers1

2

Pass a couple of arrays by “nameref” to the function.

fun() {
  local -n first_args="$1"
  local -n second_args="$2"
  local -i idx
  for idx in "${!first_args[@]}"; do
    printf 'first arg %d: %s\n' "$idx" "${first_args[idx]}"
  done
  for idx in "${!second_args[@]}"; do
    printf 'second arg %d: %s\n' "$idx" "${second_args[idx]}"
  done
  echo 'All first args:' "${first_args[@]}"
  echo 'All second args:' "${second_args[@]}"
}

one_arg_pack=(--{a..c}{0..2})
another_arg_pack=('blah blah' /some/path --whatever 'a b c')

fun one_arg_pack another_arg_pack
Andrej Podzimek
  • 2,409
  • 9
  • 12