Search code examples
arraysbashremote-serveroctalparameter-expansion

Change the base of an array elemnts from octal to decimal (inside a local bash script that run remote)


I have a problem in the bash script from below.

I'm RUNNING THE CODE AS IT IS POSTED HERE

Code of my bash script:

#! /bin/bash
CMD='
# go to a specific path
set -x
cd share/Images
# create an array, perform the extraction of dates from folders names , populate the array with dates
declare -a all_dates
j=0
s=0
all_dates=($(ls | grep -oE "[0-9]{4}-[0-9]{2}-[0-9]{2}"))
len=${all_dates[@]}
# vrification if dates are extracted correct
echo "$len"
# compare the dates
if [[ '$1' == '$2' ]]; then
echo "first important date and second important date are equal"
else
echo "first important date and second important date are different"
fi
# show the index of each elemnts and highlight the index of 2 important dates that are provided as arguments from comandline
for i in ${all_dates[@]}; do
echo "$i"
echo " Index is $j for array elemnt ${all_dates[$i]}"
# comparison with first important date
if [[ '$1' == ${all_dates[$j]} ]]; then
echo " bingo found first important date: index is $j for element ${all_dates[$j]}"
fi
# comparison with second important date
if [[ '$2' == ${all_dates[$j]} ]]; then
echo " bingo found second important date: index is $s for element ${all_dates[$j]}"
fi
j=$(($j+1))
s=$(($s+1))
done
'
ssh -t user@server << EOT
$CMD
EOT

This is the output of the code from above:

Index is 16 for array elemnt 
+ echo 2016-04-05
+ echo ' Index is 16 for array elemnt '
+ [[ 2016-03-15 == 2016-04-05 ]]
+ [[ 2016-03-26 == 2016-04-05 ]]
+ j=17
+ s=17
+ for i in '${all_dates[@]}'
2016-04-08
+ echo 2016-04-08
-sh: line 22: 2016-04-08: value too great for base (error token is "08")

Also the structure of my array elements is YYYY-MM-dd The error appear in for statement, hence the need to change the base (from octal to decimal). I have had several attempts, I think this one is the closest to the solution but I didn't suceed:

for i in "${all_dates[@]}"; do all_b+=( $((10#$i)) ) 
echo "${all_b[@]}"
done

Any help is welcome!


Solution

  • As a general rule, always quote any variable that goes into '[[' or '[' condition, unless you are able to guarantee that the value does not have any special value. In this case, this applies to anything that refer to $1, $2 or if all_dates[$j]

    # Old
    if [[ '$1' == '$2' ]]; then
    # New
    if [[ "'$1'" == "'$2'" ]]; then
    
    # Old
    if [[ '$1' == ${all_dates[$j]} ]]; then
    # New
    if [[ "'$1'" == "${all_dates[$j]}" ]]; then
    

    I might have missed a one or more instances.

    Without quotes, the script may be 'surprised' by parameters, file names with special characters, etc.