function dec_to_bin {
if [ $# != 2 ]
then
return -1
else
declare -a ARRAY[30]
declare -i INDEX=0
declare -i TEMP=$2
declare -i TEMP2=0
while [ $TEMP -gt 0 ]
do
TEMP2="$TEMP%2"
#printf "%d" "$TEMP2"
ARRAY[$INDEX]=$TEMP2
TEMP=$TEMP/2
INDEX=$[ $INDEX + 1 ] #note
done
for (( COUNT=INDEX; COUNT>-1; COUNT--)){
printf "%d" "${ARRAY[$COUNT]}" <<LINE 27
#echo -n ${ARRAY[$COUNT]} <<LINE 28
}
fi
}
why is this code giving this error
q5.sh: line 27: ARRAY[$COUNT]: unbound variable
same error comes with line 28 if uncommented
One more question, I am confused with the difference b/w ” and “” used in bash scripting any link to some nice article will be helpfull.
It works fine for me except that you can’t do
return -1. The usual error value is1.The error message is because you have
set -uand you’re starting yourforloop atINDEXinstead ofINDEX-1(${ARRAY[INDEX]}will always be empty because of the way yourwhileloop is written). Since you’re using%din yourprintfstatement, empty variables will print as “0” (ifset -uis not in effect).Also, it’s meaningless to declare an array with a size. Arrays in Bash are completely dynamic.
I would code the
forloop with a test for0(because the-1looks confusing since it can’t be the index of an numerically indexed array):This form is deprecated:
Use this instead:
or this:
I also recommend using lower case or mixed case variables as a habit to reduce the chance of variable name collision with shell variables.
You’re not using
$1for anything.