Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

bash how to shift through initial arguments passed to a function

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#!/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?

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading