每次登录远程系统时,我都想运行一些命令。无法在远程的 .bashrc
中存储命令。
在 ssh 的 bash 脚本中,在引号内转义转义字符的正确方法是什么? 如何在新行中编写每个命令?
我的剧本
#!/bin/bash
remote_PS1=$'\[\033[01;32m\]\u@\[\033[03;80m\]\h\[\033[00m\]:\[\033[01;34m\]\!:\w\[\033[00m\]\$ '
ssh -t "$@" 'export SYSTEMD_PAGER="";' \
'export $remote_PS1;' \
'echo -e "set nocompatible" > /home/root/.vimrc;' \
'bash -l;'
没有用。
答案 0 :(得分:1)
在双引号内转义转义字符并在远程服务器上运行它们对我来说太复杂了:)
相反,我为远程编写了一个 remoterc
文件和一个小的 remotessh
脚本。
在 remotessh
中,首先我在远程机器上复制 remoterc
并以交互方式使用 bash
文件运行 remoterc
命令。
远程:
#!/bin/bash
SYSTEMD_PAGER=""
PS1="\[\033[01;32m\]\u@\[\033[03;80m\]\h\[\033[00m\]:\[\033[01;34m\]\!:\w\[\033[00m\]\$ "
echo -e "set nocompatible" > /home/root/.vimrc
远程:
#!/bin/bash
scp remoterc "$1":/home/root/
ssh "$1" -t "bash --rcfile remoterc -i"
它有效:)
答案 1 :(得分:1)
您可以使用 Bash 的 printf %q
。
根据help printf
:
%q
以可重用为 shell 输入的方式引用参数
看下面的例子:
$ cat foo.sh
ps1='\[\033[1;31m\]\u:\w \[\033[0m\]\$ '
ps1_quoted=$( printf %q "$ps1" )
ssh -t foo@localhost \
'export FOO=bar;' \
"export PS1=$ps1_quoted;" \
'bash --norc'
结果: