Jochen Richter
Jochen Richter

Reputation: 23

Passing quoted variables in remote ssh command

I want to grep through a few files for a string. In this example I want to grep for "test 1234"

#!/bin/bash

variable="test 1234"
ssh root@server "grep "$variable" /path/*"

This script doesn't work because test 1234 is passed to the server instead of "test 1234"

How can I fix this?

Upvotes: 2

Views: 2840

Answers (2)

adampolar
adampolar

Reputation: 46

You should be able to escape the double quotes with a \ backslash character.

see escape double quote in grep

Upvotes: 1

arco444
arco444

Reputation: 22821

You need to escape the quotes around $variable in your command:

ssh root@server "grep \"$variable\" /path/*"

As it stands, the variable is expanding but because the quotes aren't escaped, the command is searching for the text test in the files 1234 and /path/*

Upvotes: 3

Related Questions