mikcutu mikcutu - 6 months ago 9
Linux Question

ubnormal 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

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

set -o noglob 
Comments