Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use $array=() in bash?

Tags:

arrays

bash

Two things, first this is my first question in this forum and I do apologise if the formating is all over the place. Second I have not written that many bash scripts, and it tend to be quite a long time between the scripts I produce.

That said, here is my question.

Is it possible to do something like this in bash (Clear array $array contains):
$array=()

Basically this is what I would like to do. I have a variable with array variable names in it:

array1=()  
array2=()  
arrayList="array1 array2"  


# In a function far far away
for array in $arrayList
do  
    eval arr=("\"\${$array[@]\"")  

    for index in ${!arr[@]}
    do
        echo "${arr[$index]}"
    done
    # Here is the big "?", I like to clear the array that $array refers to.
    $array=()  
done

My arrays contain strings that include "" (space) and this is why I use the eval statement. Not sure it's needed but at least it's working. The script is more or less working as I want it too, but I need to clear the arrays in the $arrayList, and I rather not hardcode it somewhere, even though that would be easy.

like image 807
Qben Avatar asked May 08 '12 11:05

Qben


2 Answers

Probably the simplest thing to do is just unset them. An unset variable will act identically to an empty array in most contexts, and unset $array ought to work fine.

like image 126
FatalError Avatar answered Nov 20 '22 06:11

FatalError


You can't do $foo=bar ever -- that isn't how indirect assignments in bash work. Unfortunately, while being able to do indirect array assignments is an available feature in ksh93, it isn't a formally documented available feature in bash.

Quoting BashFAQ #6 (which should be read in full if you're interested in knowing more about using indirect variables in general):

We are not aware of any trick that can duplicate that functionality in POSIX or Bourne shells (short of using eval, which is extremely difficult to do securely). Bash can almost do it -- some indirect array tricks work, and others do not, and we do not know whether the syntax involved will remain stable in future releases. So, consider this a use at your own risk hack.

# Bash -- trick #1.  Seems to work in bash 2 and up.
realarray=(...) ref=realarray; index=2
tmp="$ref[$index]"
echo "${!tmp}"            # gives array element [2]

# Bash -- trick #2.  Seems to work in bash 3 and up.
# Does NOT work in bash 2.05b.
tmp="$ref[@]"
printf "<%s> " "${!tmp}"; echo    # Iterate whole array.

However, clearing is simpler, as unset $array will work fine.

like image 40
Charles Duffy Avatar answered Nov 20 '22 08:11

Charles Duffy