首页 > 解决方案 > 使用访问远程服务器的 bash 脚本打印数组元素的问题

问题描述

我编写了一个 bash 脚本,它仅从文件夹名称中提取日期,并将提取的内容(日期)放入数组中以执行其他操作。本地工作正常,当我想在服务器上执行此远程操作时出现问题。

我通过 ssh 访问服务器,从文件夹名称中提取日期的部分工作正常,主要问题是当我想用日期填充数组时。

以下是我脚本中的一些代码:

#! bin/bash

ssh -t -t user@serveradress << 'EOT'

 # go in the path where to perform the extraction of dates
cd share/Pictures_G

 # create an array, perform the extraction of dates , populate the array with dates

declare -a all_dates

all_dates=($(ls | grep -o "[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}"))
len=${all_dates[@]}
echo "$len"
EOT

因此,该命令ls | grep -o "[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}"可以单独运行,但是当我以上面脚本中使用的方式使用它时,会提供下一个输出:

all_dates=
len=
echo

据我了解,没有任何东西传递给数组。

标签: arraysbashsshgrepremote-server

解决方案


您真的需要将信息存储在数组中吗?如果没有,这是恕我直言,一个可读的解决方案:

#!/bin/bash

for file in $(find . -type f); do
  echo "File: $file";
  echo "Date: $(grep 'pattern' <<< "$file")"
done

推荐阅读