2

I've written a bash script that should take in inputs, connect to a remote server, and run a series of commands using the given inputs. It will end up being much more complicated than this but here is a very simple example:

#!/bin/bash
NAME=$1
echo $NAME
ssh user@server "ls $NAME"

If I hard code the file name into the bash script's ssh command, I get a response and if I type these exact lines, setting $NAME to my file name, into the command line, I get the correct response but the combination of passing in the file name to the script and attempting to return the "ls" returns an error stating that there is "no such file or directory". It does echo the file name I give it so it's being stored correctly in $NAME. What am I doing wrong?

3
  • 2
    Whats the file name? Commented Jan 20, 2017 at 6:21
  • 3
    Do an ls w/o the name and/or a pwd to make sure the other end what you expect. Commented Jan 20, 2017 at 6:42
  • 1
    It's always a good idea to quote your variables. Won't fix your issue but may help later down the line. For example echo "$NAME" Commented Jan 20, 2017 at 11:39

1 Answer 1

3

If $NAME contains characters that are expanded in some way by the shell (such as spaces or $) then you will run into troubles. You have to escape them. This quickly get very hairy. To catter for all cases you have to put the filename in a file that you copy to the remote and then use the content as argument to your command. Something like:

NAME="$1"
TMPF=/tmp/tmpf-$$ # If you have mktemp then use that instead
printf %s "$NAME" >$TMPF
scp "$TMPF" user@server:$TMPF
ssh user@server "ls \"$(cat $TMPF)\""
2
  • 1
    I agree with your assessment of what is probably happening. However, such machinations are hardly necessary. This should work: ssh user@server " ls '$NAME' " -- the outer string with double quotes will allow the variable to be expanded, while the single quotes will get sent to the server so it becomes a literal with spaces. Commented Jan 20, 2017 at 8:04
  • 2
    @Angelo … Unless $NAME contains a ' character. Commented Jan 20, 2017 at 8:21

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.