0

我在下面的 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-ddfor语句中出现错误,因此需要更改基数(从八进制到十进制)。我进行了几次尝试,我认为这是最接近解决方案的一个,但我没有成功:

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

欢迎任何帮助!

4

2 回答 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

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

如果没有引号,脚本可能会对参数、带有特殊字符的文件名等感到“惊讶”。

于 2019-11-29T10:34:07.757 回答
0

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

阅读这篇文章也帮助了我 Value too great for base(错误标记是“09”)

于 2019-12-02T09:10:57.263 回答