RandyWong RandyWong - 14 days ago 6
Bash Question

Can read command in shell be use in assign string to array and reset default array

function get_path
{
<HERE>
if [ $TYPE= 'MUSIC' ]
then
FILELIST_TEMP+=("/data/user/DOWNLOAD,/data/user/MUSIC")
IFS=',' read -r -a FILELIST_PATH <<< "$FILELIST_TEMP"
elif [ $TYPE= 'IMAGE' ]
FILELIST_PATH+=("/data/user/IMAGE")
fi
}


The code above is use to store Folder path into an array .There are 2 situation where one of variable has 1 string or 2 string.

1)Can read command be use to assign string to an array and how to do it ?(IMAGE part)

2)Does ARRAY+="value" equal to append new value to array ?It does not reset array to default 0 first then append ?

3a)If the above code is called from main and I declare
declare -a FILELIST_PATH=()
at
<HERE>
.When I tried test by calling total number of array in
FILELIST_PATH
it display at zero.

3b)Correct me if I am wrong
read -r -a FILELIST_PATH
is also the same as
declare -a FILELIST_PATH=()
it resets the array to 0 but it is accessible at the main function even it is declared at
function_get_path
Why is that ?

Output desired:

/data/user/DOWNLOAD
/data/user/MUSIC

/data/user/IMAGE

Answer

1) Yes, the -a option allows you to read into an array.

2) ARRAY+="value" doesn't append to the array, it has to be ARRAY+=("value"). ARRAY+="value" concatenates value to ARRAY[0]. Neither of them resets the array.

3a) When you use declare inside a function, the variable is local to the function, unless you use the -g option to make it a global variable.

3b) You have to use declare or local to declare local variables. If you simply assign to an undeclared variable with VAR=value or read VAR, it's not declared locally so it creates a global variable.

FYI, the standard syntax for defining functions is like this:

get_path() {
    <HERE> 
    if [ $TYPE= 'MUSIC' ]
    then
        FILELIST_TEMP+=("/data/user/DOWNLOAD,/data/user/MUSIC")
        IFS=',' read -r -a FILELIST_PATH <<< "$FILELIST_TEMP"
    elif [ $TYPE= 'IMAGE' ]
        FILELIST_PATH+=("/data/user/IMAGE")
    fi
}

function get_path is a bash extension.