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?

closed as unclear what you're asking by user34720, roaima, Julie Pelletier, G-Man Says 'Reinstate Monica', Michael Homer Jan 21 '17 at 6:33

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 2
    Whats the file name? – heemayl Jan 20 '17 at 6:21
  • 3
    Do an ls w/o the name and/or a pwd to make sure the other end what you expect. – Stephen Rauch Jan 20 '17 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" – roaima Jan 20 '17 at 11:39
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)\""
  • 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. – Angelo Jan 20 '17 at 8:04
  • 2
    @Angelo … Unless $NAME contains a ' character. – kmkaplan Jan 20 '17 at 8:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.