Home > OS >  Bash: passing different lists of arguments to a function
Bash: passing different lists of arguments to a function

Time:11-01

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?

CodePudding user response:

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
  • Related