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

问题描述 投票:0回答:2

我在下面的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

欢迎任何帮助!

arrays bash remote-server octal parameter-expansion
2个回答
1
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.