将数组元素的基数从八进制更改为十进制(在 运行 远程的本地 bash 脚本中)

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

下面的 bash 脚本有问题。

我是 运行 这里发布的代码

我的 bash 脚本代码:

#! /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 [[ '' == '' ]]; 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 [[ '' == ${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 [[ '' == ${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

这是上面代码的输出:

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")

我的数组元素的结构也是 YYYY-MM-dd 错误出现在 for 语句中,因此需要更改基数(从八进制到十进制)。我已经尝试了几次,我认为这个是最接近解决方案的,但我没有成功:

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

欢迎任何帮助!

作为一般规则,始终引用进入“[[”或“[”条件的任何变量,除非您能够保证该值没有任何特殊值。在这种情况下,这适用于任何引用 $1、$2 或如果 all_dates[$j]

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

我可能错过了一个或多个实例。

没有引号,脚本可能'surprised'由参数、文件名带特殊字符等组成

阅读更多内容后,我找不到更改我的案例的八进制基数的方法。解决方案是删除月份和日期的前导 0 以具有这种格式 2016-4-8。我使用 sed 并使用此 all_dates=($(ls | grep -oE "[0-9]{4}-[0-9]{2}-[0-9]{2}" | sed -e 's/-0/-/g')).

从我的代码中更改行 nr.10 来完成此操作

阅读这篇文章 post 对我也有帮助 Value too great for base (error token is "09")