Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent ssh from breaking up shell script parameters

Tags:

linux

bash

ssh

I have a script, which is essentially a wrapper around an executable by the same name on a different machine. For the sake of example, i'll wrap printf here. My current script looks like this:

#!/bin/bash
ssh [email protected]. printf "$@"

Unfortunately, this breaks when one of the arguments contains a space, e.g. i'd expect the following commands to give identical outputs.:

~$ ./wrap_printf "%s_%s" "hello world" "1"
hello_world1_
~$ printf "%s_%s" "hello world" "1"
hello world_1

The problem gets even worse when (escaped) newlines are involved. How would I properly escape my arguments here?

like image 901
Ondergetekende Avatar asked Jul 06 '11 06:07

Ondergetekende


1 Answers

Based on the answer from Peter Lyons, but also allow quotes inside arguments:

#!/bin/bash
QUOTE_ARGS=''
for ARG in "$@"
do
  ARG=$(printf "%q" "$ARG")
  QUOTE_ARGS="${QUOTE_ARGS} $ARG"
done

ssh [email protected]. "printf ${QUOTE_ARGS}"

This works for everything i've tested so far, except newlines:

$ /tmp/wrap_printf "[-%s-]" "hello'\$t\""
[-hello'$t"-]
like image 91
Ondergetekende Avatar answered Sep 28 '22 02:09

Ondergetekende