1

I want to send multiple parameters to a function in bash. How can I accomplish this so the function parses though each parameter properly?

Would like to avoid having to use eval if possible.

Here is the code I am trying to use.

#!/bin/bash

arr_files=(
test_file
test_file1
test_file2
)

user=user10
group=user10

cp_chmod_chown(){
    # $1 = chmod value
    # $2 = chown value
    # $3 = array of files

    chmod_value=$1
    shift
    chown_value=$2
    shift
    arr=("$@")
 
    for i in "${arr[@]}"; do
        echo arr value: $i
    done
    echo chmod_value: $chmod_value
    echo chown_value: $chown_value

}

cp_chmod_chown "644" "$user:$group" "${arr_files[@]}"


However I am not able to shift out of the first two parameters properly so the parameters get jumbled together in the array. Here is the output after running the above script, you can see chown_value is the first value in the array for some reason:

# ./cp_arra_chmod_chown.sh

arr value: test_file
arr value: test_file1
arr value: test_file2
chmod_value: 644
chown_value: test_file

I tried putting the parameters in different orders, and using quotes and not using quotes, nothing I tried seems to work. How can I pass multiple parameters to a function?

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
Dave
  • 727
  • 1
  • 9
  • 20
  • 1
    I initially closed this as a dup of https://stackoverflow.com/q/16461656/1745001 as the original subject indicated it was about passing an array to a function, but I see now it actually has nothing to do with passing an array, it's just about passing args to a function and the fact that some of them start out as array contents is totally irrelevant so I updated the question to move all the irrelevant parts. – Ed Morton Feb 24 '22 at 14:37

1 Answers1

5

After shift, all values get shifted. Next code is wrong, as after first shift, former $2 becomes $1 :

chmod_value="$1"
shift
chown_value="$2"
shift

You should instead write :

chmod_value="$1"
shift
chown_value="$1"
shift

Or, if you prefer:

chmod_value="$1"
chown_value="$2"
shift 2
Bruno
  • 580
  • 5
  • 14