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?

3
  • 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 Commented Oct 31, 2021 at 9: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 Commented Oct 31, 2021 at 20:21
  • I've tried the solution from 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. Commented Oct 31, 2021 at 20:32

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.