Skip to content
Advertisement

empty an existing array in ksh

I have script which stores the list of files in an array as shown below

set -A my_array $(ls -tr $INPUT_DIRECTORY/*)

I have to empty this my_array variable to use it for other purpose. I cannot declare another new array.

Is there any way to clear the content of the array and reuse it again?

Thanks in advance.

Advertisement

Answer

Since you’re already using set -A … to clear the array you could issue:

set -A my_array

To re-use the array:

set -A my_array $(command to generate new data set)

For example:

$ cd /
$ set -A my_array $('ls' -tr sys)
$ echo ${my_array[@]}
kernel devices module bus class fs block power firmware dev
$ set -A my_array $('ls' -tr var)
$ echo ${my_array[@]}
opt crash X11R6 mail games yp spool lib adm cache lock tmp log run
$ set -A my_array
$ echo ${my_array[@]}
  <<no output>>

Or you could use a looping construct, eg:

for i in ${!my_array[@]}
do
    unset my_array[${i}]
done

For example:

$ set -A my_array $('ls' -tr var)
$ echo ${my_array[@]}
opt crash X11R6 mail games yp spool lib adm cache lock tmp log run
$ for i in ${!my_array[@]}
do
    unset my_array[${i}]
done
$ echo ${my_array[@]}
  <<no output>>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement