在bash“Here Document”中存储命令输出

时间:2014-01-03 11:21:57

标签: linux bash

下面是一个小的bash脚本。连接到服务器后的预期输出是打印Hello World,在下一行打印当前月份和年份 - 如Jan 2014。要在“此处文档”中使用VARIABLE1,我需要扩展美元,因此不会引用终止字符~

VARIABLE1="World"
ssh username@server.domain.com <<~
        echo "Hello $VARIABLE1"
        COMMAND1=`date +%b`
        COMMAND2=$(date +%Y)
        echo "$COMMAND1 $COMMAND2"
~

我得到的实际输出是:

Pseudo-terminal will not be allocated because stdin is not a terminal.
Password:
Hello World

在详细模式下运行ssh时,这是输出的最后一部分:

debug1: Authentications that can continue: publickey,password,keyboard-interactive
debug1: Next authentication method: publickey
debug1: Trying private key: *****
debug1: Trying private key: *****
debug1: Next authentication method: keyboard-interactive
Password:
debug1: Authentication succeeded (keyboard-interactive).
debug1: Final hpn_buffer_size = *****
debug1: HPN Disabled: 0, HPN Buffer Size: *****
debug1: channel 0: new [client-session]
debug1: Enabled Dynamic Window Scaling

debug1: Requesting no-more-sessions@openssh.com
debug1: Entering interactive session.
Hello World

debug1: client_input_channel_req: channel 0 rtype exit-status reply 0
debug1: channel 0: free: client-session, nchannels 1
debug1: fd 0 clearing O_NONBLOCK
Transferred: sent 1552, received 2360 bytes, in 0.1 seconds
Bytes per second: sent 17253.2, received 26235.6
debug1: Exit status 0

有人可以指出这里的错误吗?为什么不打印Jan 2014

1 个答案:

答案 0 :(得分:2)

有一些关于如何强制使用tty的信息here,但是,如果你正确地逃避了你的角色,你的脚本应该可以工作:

VARIABLE1="World"
ssh username@server.domain.com <<EOF
        echo Hello $VARIABLE1
        COMMAND1=\`date +%b\`
        COMMAND2=\$(date +%Y)
        echo "\$COMMAND1 \$COMMAND2"
EOF

如果你想强制tty:

ssh -t -t user@domain.com <<EOF
        echo Hello $VARIABLE1
        COMMAND1=\`date +%b\`
        COMMAND2=\$(date +%Y)
        echo "\$COMMAND1 \$COMMAND2"
        exit
EOF

或者,您可以将脚本作为参数发送到ssh:

ssh user@domain.com "echo Hello $VARIABLE1;COMMAND1=\`date +%b\`; COMMAND2=\$(date +%Y); echo \$COMMAND1 \$COMMAND2"

编辑:如果要禁用有关伪终端分配的消息,请使用“-T”:

VARIABLE1="World"
ssh -T username@server.domain.com <<EOF
        echo Hello $VARIABLE1
        COMMAND1=\`date +%b\`
        COMMAND2=\$(date +%Y)
        echo "\$COMMAND1 \$COMMAND2"
EOF