[SOLVED] bash how to shift through initial arguments passed to a function

Issue

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=("[email protected]")
 
    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?

Solution

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

Answered By – Bruno

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.