我正在通过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/