Mubin Icyer
Mubin Icyer

Reputation: 705

Using escape characters inside double quotes in ssh command in bash script

I want to run some commands each time when I log in to a remote system. Storing commands in .bashrc on remote is not an option.

What is the proper way to escape the escape chars inside of quotes in bash script for ssh? How can I write each command in new line?

My script

#!/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;'

didn't work.

Upvotes: 1

Views: 1420

Answers (2)

pynexj
pynexj

Reputation: 20688

You can use Bash's printf %q.

According to help printf:

%q      quote the argument in a way that can be reused as shell input

See the following example:

$ 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'

Result:

pic

Upvotes: 2

Mubin Icyer
Mubin Icyer

Reputation: 705

Escaping escape characters inside double-quotes and run them on remote server is way too complicated for me :) Instead, I wrote a remoterc file for remote and a small remotessh script. In remotessh, first I copy remoterc on remote machine and run bash command with that remoterc file interactively.

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 

remotessh:

#!/bin/bash 
scp remoterc "$1":/home/root/ 
ssh "$1" -t "bash --rcfile remoterc -i"

It works :)

Upvotes: 2

Related Questions