bash - 多行ssh命令,用于

标签 bash ssh heredoc

我正在通过bash执行命令的ssh脚本。

FILENAMES=(
  "export_production_20200604.tgz"
  "export_production_log_20200604.tgz"
  "export_production_session_20200604.tgz"
  "export_production_view_20200604.tgz"
)

sshpass -p $PASSWORD ssh -T $LOGIN@$IP '/bin/bash' <<EOF
  for f in "${FILENAMES[@]}"; do
    echo Untar "$f"
  done
EOF

问题是当我执行脚本时,$f为空。

我在线查看了多个解决方案来执行多个命令,但是没有一个可行的方法:

link 1

link 2

...

你能帮我弄清楚吗?

注意:

执行:
for f in "${FILENAMES[@]}"; do
    echo Untar "$f"
done

<<EOF之外EOF起作用

在本地:

bash 4.4.20(1)-发布

远程:

bash 4.2.46(2)-发布



编辑:技巧

时间紧迫,别无选择,我实现了@ hads0m提供的解决方案,可能会帮助遇到相同问题的其他开发人员:
# $1 the command
function executeRemoteCommand() {
    sshpass -p $DB_PASSWORD ssh $DB_LOGIN@$DB_SERVER_IP $1
}

for i in "${!FILENAMES[@]}"; do
    f=$FILENAMES[$i]

    DB_NAME=$DB_NAMES[$i]

    # Untar the file
    executeRemoteCommand '/usr/bin/tar xzvf '$MONGODB_DATA_PATH'/'$TMP_DIRECTORY'/'$f' --strip-components=1'

    # Delete the tar
    executeRemoteCommand 'rm -f '$MONGODB_DATA_PATH'/'$TMP_DIRECTORY'/'$f''

    # Restore the database
    executeRemoteCommand 'mongorestore --host 127.0.0.1:'$DB_PORT' --username "'$MONGODB_USER'" --password "'$MONGODB_PASSWORD'" --authenticationDatabase admin --gzip "'$DB_NAME'" --db "'$DB_NAME'"'
done

最佳答案

您需要转义$符号以避免它在本地扩展,并将该数组传递到远程。

这可能是您想要的:

#!/usr/bin/env bash

FILENAMES=(
      "export_production_20200604.tgz"
      "export_production_log_20200604.tgz"
      "export_production_session_20200604.tgz"
      "export_production_view_20200604.tgz"
)

sshpass -p $PASSWORD ssh -T $LOGIN@$IP '/bin/bash' <<EOF
  $(declare -p FILENAMES)                                                                       
  for f in "\${FILENAMES[@]}"; do                                                               
    echo Untar "\$f"                                                                            
  done                                                                                          
EOF

关于bash - 多行ssh命令,用于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62212882/

相关文章:

Python 2.7.1 看不到 Twisted

ssh - 如何配置nginx通过subdomain.domain.tld :80 available创建ssh服务器

linux - 如何将 ssh key 添加到远程服务器?

bash - 管道 heredoc 的多行语法;这是可移植的吗?

ruby - 了解 ruby 奎因

php - 什么是 <<<_END?

linux - BASH:如果目录中的文件数为 2 或更多,则需要运行 if 语句

bash - sh脚本在docker容器中不起作用

python - 允许命令在 bash 脚本中后台运行 django runserver 命令后运行?

Linux ssh 无密码登录不起作用?