Un grand merci à "Gavin Smith" sur stackoverflow.com pour la première partie de cette astuce.
Les expressions comme ${${a}} ne fonctionnent pas. Pour contourner ce problème, vous pouvez utiliser eval :
b=value a=b eval aval=\$$a echo $avalLa sortie est
value
Merci pour le conseil Gavin !
Ok, alors pourquoi voudriez-vous ?
Pour moi, j'avais besoin de tester que certaines variables étaient définies à partir d'un fichier de configuration inclus. En utilisant une boucle et la technique d'imbrication ci-dessus, nous pouvons prendre :
Ceci :
if [ "${KIDFILE}" == "" ] ; then
echo "ERROR - KIDFILE Not Set"
exit 1
fi
if [ "${KUSER}" == "" ] ; then
echo "ERROR - KUSER Not Set"
exit 1
fi
if [ "${KSERVER}" == "" ] ; then
echo "ERROR - KSERVER Not Set"
exit 1
fi
if [ "${KRFILE}" == "" ] ; then
echo "ERROR - KRFILE Not Set"
exit 1
fi
if [ "${KLFILE}" == "" ] ; then
echo "ERROR - KLFILE Not Set"
exit 1
fi
if [ "${KLINK}" == "" ] ; then
echo "ERROR - KLINK Not Set"
exit 1
fi Et remplacez-le par le plus élégant :
NEEDVARS="KIDFILE KUSER KSERVER KRFILE KLFILE KLINK"
for MYVAR in ${NEEDVARS}; do
eval MYVAL=\$${MYVAR}
if [ "${MYVAL}" = "" ] ; then
echo "${MYVAR} NOT SET"
exit 1
fi
done