Discussion:
[Help-bash] Bash - variable identifier with "-"
Felipe Salvador
2018-04-04 18:09:59 UTC
Permalink
Hi,
I have this code

--
#!/bin/bash
set -x

list="dragon cvlc rhythmbox totem-audio-preview radiotray"

for p in $list
do
which $p 1>/dev/null
yesno=$?
if [ "$yesno" -ne 0 ]; then
declare $p="NO"; else
declare $p="SÌ"
fi
done

cat<<EOF

Utilizzo: $(basename $0) [OPZIONE]

OPZIONI SUPPORTATE: INSTALLATO:

-dp Utilizza Dragonplayer $dragon
-vp Utilizza (c)VLC $cvlc
-rp Utilizza Rhythmbox $rhythmbox
-tp Utilizza totem-audio-preview $totem-audio-preview
-rtp Utilizza radiotray $radiotray

EOF
--

It return

--
+ list='dragon cvlc rhythmbox totem-audio-preview radiotray'
+ for p in $list
+ which dragon
+ yesno=0
+ '[' 0 -ne 0 ']'
+ export dragon=SÌ
+ dragon=SÌ
+ for p in $list
+ which cvlc
+ yesno=0
+ '[' 0 -ne 0 ']'
+ export cvlc=SÌ
+ cvlc=SÌ
+ for p in $list
+ which rhythmbox
+ yesno=1
+ '[' 1 -ne 0 ']'
+ export rhythmbox=NO
+ rhythmbox=NO
+ for p in $list
+ which totem-audio-preview
+ yesno=1
+ '[' 1 -ne 0 ']'
+ export totem-audio-preview=NO
/home/felipe/prog: riga 11: export: "totem-audio-preview=NO": non è un identificatore valido
+ for p in $list ^^^
+ which radiotray not valid identifier
+ yesno=1
+ '[' 1 -ne 0 ']'
+ export radiotray=NO
+ radiotray=NO
+ cat
++ basename /home/felipe/prog

Utilizzo: prog [OPZIONE]

OPZIONI SUPPORTATE: INSTALLED:

-dp Utilizza Dragonplayer SÌ
-vp Utilizza (c)VLC SÌ
-rp Utilizza Rhythmbox NO
-tp Utilizza totem-audio-preview -audio-preview
-rtp Utilizza radiotray NO
--

For what I understand[¹] there is no way to get it work, due to the
identifier "naming design". I'm wrong? Please, tell me there is a way
to get out form this situation.

Tia


[¹] http://www.tldp.org/LDP/Bash-Beginners-Guide/html/sect_03_02.html

Regards
--
Felipe Salvador
Greg Wooledge
2018-04-04 18:22:04 UTC
Permalink
Post by Felipe Salvador
#!/bin/bash
set -x
list="dragon cvlc rhythmbox totem-audio-preview radiotray"
Use an array to store a list of strings, not a string. Also prefer a
more descriptive name than "list". What is it a list OF?
Post by Felipe Salvador
declare $p="NO"; else
Use an associative array to store a mapping from strings to values.

Also, don't use which(1).


#!/bin/bash
apps=(dragon cvlc rhythmbox totem-audio-preview radiotray)
declare -A found

for app in "${apps[@]}"; do
if command -v "$app" >/dev/null; then
found[$app]=1
else
found[$app]=0
fi
done

And so on.

Loading...