Mayerz Mayerz - 1 month ago 7
Bash Question

Can't empty a bash array (bash --version 3.2.25)

My bash array never empty itself.

I am using bash 3.2.25.
I tried using the folowing methods:

declare -a array

# fill array...

# 1
array=()

# 2
empty_array=()
array=( "${empty_array[@]}" )

# 3
unset array


My array never get emptied, am I doing something wrong?

Full code as requested :

declare -a array

function get_array() {

#active_tills=()

#unset active_tills

#active_tills=( "${active_tills[@]}" )

# fill array
while read -r line || [[ -n "$line" ]]; do
line=$(echo "$line" | cut -d' ' -f1)
if [ -n "$line" ] ; then
to_add+="$line "
fi
done < "$request_tmp"
array=($(echo $to_add))
return 0
}


Then

get_array
for host in "${array[@]}"; do
echo "=> $host"
done
# 1
# 2
# 3

get_array
for host in "${array[@]}"; do
echo "=> $host"
done
# 1
# 2
# 3
# 1
# 2
# 3

Answer

to_add is also a global variable, and you don't reset its value before appending to it. However, you don't need it: you can append directly to the array.

declare -a array

function get_array() {

  local line rest

  array=()
  while read -r line rest || [[ -n "$line" ]]; do
    if [ -n "$line" ] ; then
      array+=("$line")
    fi
  done < "$request_tmp"
  return 0
}

As an aside, if you can guarantee that the input file ends with a newline (as is required of a proper text file in POSIX), you don't need the || [[ -n $line ]] hack in your while loop.