mikcutu mikcutu - 6 months ago 10
Linux Question

Abnormal behavior when parsing an array

Since yesterday I am facing with a strange behavior of shell code.

This is the code:

#!/bin/bash

operatori="/*-+="


temp=$1
len_temp=${#temp}

for (( i=0; i<$len_temp; i++ ))
do
array[i]=${temp:i:1}
#echo 'i= '${array[i]}
done

for i in ${array[@]}
do
if [[ "$operatori" =~ "$i" ]]; then
echo '@@'$i
fi
done


It is executed with
$1 = tom*jerry-1=0
.
In this version of the code , i expect to return:

@@*
@@-
@@=


But it returns just

@@-
@@=


On the other hand, I tried to deny the condition, having

if ! [[ "$operatori" =~ "$i" ]]; then


But the result is more strange:

@@t
@@o
@@m
@@analyzer.sh
@@gnome-terminal.desktop
@@mount location.sh
@@test.sh
@@j
@@e
@@r
@@r
@@y
@@1
@@0


Where I expect to receive:

@@t
@@o
@@m
@@j
@@e
@@r
@@r
@@y
@@1
@@0


where the analyzer.sh, gnome-teminal.desktop, mount location.sh, test.sh represents some files from the same location where my code is saved.

Can anyone tell me what am I doing wrong?

Answer

You can set bash to noglob as first command of your script to prevent globbing with * :

set -o noglob

Update :

Use set +o noglob to set noglob back to off when your script needs wildcard expansion :

set -o noglob
for i in ${array[@]}
  do
    if [[ "$operatori" =~ "$i" ]]; then
      echo '@@'$i
    fi
  done
set +o noglob

Note : @mikcutu, the noglob solution is a (working) workaround. See @Gordon Davisson's answer for details about why you first should double-quote your variables to prevent word splitting.

Comments