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

下面的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 [[ '$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

这是上面代码的输出:

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

欢迎任何帮助!

bohaooffice 回答:将数组元素的基数从八进制更改为十进制(在远程运行的本地bash脚本内部)

作为一般规则,除非可以保证该值没有任何特殊值,否则请始终引用进入“ [[”或“ [””条件的任何变量。在这种情况下,这适用于引用$ 1,$ 2或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

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

不带引号的脚本可能会因参数,带有特殊字符的文件名等而“感到惊讶”。

,

阅读更多内容后,我找不到改变我的情况的八进制基数的方法。解决方案是从月和日中删除前导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行。

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

本文链接:https://www.f2er.com/3013637.html

大家都在问