How should I be using variables in bash shell sending heredoc section over ssh?

廉价感情. 提交于 2019-12-12 01:24:27

问题


I have a bash script that I am trying to reconfigure to remove some hardcoded values.

The script sets a variable with the content from a heredoc section and that variable is passed through to the remote server via ssh.

#!/bin/bash
FILEREF=${1}
CMDS=$(cat <<HDOC
    echo $FILEREF
    COUNT=$(timeout 10s egrep -c -m 1 'INFO: Destroying ProtocolHandler \["http-bio-8080"\]' <(tail -n0 -f ~/tomcat/logs/catalina.out))
    # removed a load of other stuff for brevity
HDOC
)

#/usr/bin/ssh.exe -t -t -o TCPKeepAlive=yes -o ServerAliveInterval=45 -i "$PRIVATE_KEY_PATH" "$REMOTE_USER"@"$REMOTE_HOST" "$CMDS"

The vars given to the ssh command (under cygwin, hence .exe) are set earlier in the script as params.

The problem I have is that the local machine is attempting to run the command that is assigned to COUNT. I want that to be passed to the remote host as is.

So I could wrap HDOC in "", to prevent parsing of stuff, but then the $FILEREF is sent as a literal string, but I want the value of that variable to be sent.

So I guess I need a way of refactoring this part of the script so I can work in both ways, some commands passed as literal strings to be executed remotely, some I want to pass the value of.

Can you suggest an appropriate refactor?


回答1:


It's possible to send environment variables themselves via ssh -o SendEnv …; however, the names of such variables need to be preconfigured in the receiving sshd_config, so it's only worth doing if you need to do it more than once on the same machine. You can also compose what you're redirecting to ssh via a compound command:

{
    printf 'echo %s\n' "$FILEREF"
    cat << 'HDOC'
      COUNT=$(timeout 10s egrep -c -m 1 'INFO: Destroying ProtocolHandler \["http-bio-8080"\]' <(tail -n0 -f ~/tomcat/logs/catalina.out))
      # other stuff
    HDOC
} | ssh …



回答2:


Current solution:

VARS=$(cat <<-SETVARS
UNPACKED_WAR="$(echo $WAR_FILE_REMOTE_NAME | sed 's/.war//')"
WAR_FILE="$WAR_FILE_REMOTE_NAME"
SETVARS
)
CMDS=$(echo "$VARS"; cat <<"HDOC"
     # as original question
HDOC
/usr/bin/ssh.exe -t -t -o TCPKeepAlive=yes -o ServerAliveInterval=45 -i "$PRIVATE_KEY_PATH" "$REMOTE_USER"@"$REMOTE_HOST" "$CMDS"

So I parse the variable creation bits into their own variable and concat the 2 HDOC blocs. Not very pretty, but it seems to work!



来源:https://stackoverflow.com/questions/23631996/how-should-i-be-using-variables-in-bash-shell-sending-heredoc-section-over-ssh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!