在使用可远程访问服务器的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

根据我的理解,什么都不会传递给数组。

m13432900836 回答:在使用可远程访问服务器的bash脚本打印数组元素时出现问题

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

#!/bin/bash

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

当您通过here documents传递多行字符串时,文本将受到参数扩展,命令替换等限制。

相反,请考虑使用单引号定义要执行的命令(避免所有替换),然后将其通过here document传递。鉴于命令不使用单引号,因此相对简单。

#! /bin/bash
CMD='

 # 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"
'
ssh -t -t user@serveradress <<EOT
    $CMD
EOT

等效方法,没有中间变量

echo '
 # PUT COMMANDS HERE
 # go in the path where to perform the extraction of dates
cd share/Pictures_G
 # MORE COMMANDS HERE
...
echo "$len"
' | ssh -t -t user@serveradress

**UPDATE 1: Parameterizing the command**

If the command line has to be parametrized to using variables in the calling script,they should be placed into double quotes,instead of single quotes. For example,if TARGET_DIR reference the remote path. Note that the single quote has to be terminated,and the variable should be placed in double quotes for safety.

TARGET_DIR =共享/图片_G CMD ='  #进入执行日期提取的路径 cd'“ $ TARGET_DIR”'

#创建一个数组,执行日期提取,用日期填充数组

声明-a all_dates

all_dates =($(ls | grep -o“ [0-9] {4}-[0-9] {2}-[0-9] {2}”)) len = $ {all_dates [@]} 回声“ $ len” '


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

大家都在问