scp and line break in a shell script

4

I have an .sh file, containing a command, which copies a file from remote server to a particular directory, preserving original filename, and the second line is just a comment:

scp (host):~/filename.sql ~/
# just a comment

I name the script dbcopy.sh, put it in my home directory and run it from console like:

sh ~/dbcopy.sh

The problem is because of a line break following the scp command, the file being copied has a name consisting of one character (in the listing below it is displayed as a question mark) instead of an original name!

console> ls -l ~
...
-rw-rw-r--  1 (user)  (group)   158327960 26 oct 17:28 ?

If I remove any line breaks after the scp command everything works as expected.

How should I handle this situation?

1234ru

Posted 2016-10-24T08:45:22.267

Reputation: 81

Any chance you can post exactly what you have in the shell script and how you are running the script? – Tigger – 2016-10-24T09:56:23.397

@Tigger, I've updated the original question and posted the shell script. It turned out the issue is because of a line break following the command. I didn't mind it at first, cause initially what followed the command was just a comment. – 1234ru – 2016-10-24T16:09:08.033

I can not replicate the issue at all. At first I thought the lack of the header #!/bin/sh may have been the problem but that is not the case. My test script worked with and without the header. What OS is this on? Also, what happens if you add echo ~/ before the scp line? – Tigger – 2016-10-27T08:36:27.977

@Tigger, I figured it out. Read my answer to myself - it turned out to be really funny :D Thank you for your assistance! – 1234ru – 2016-10-31T19:04:23.787

Answers

1

The issue was line ending delimiter in my editor: it used \r\n sequence instead of just \n. Thus the last argument of scp command was not just ~/ as it displays. It was actually ~/\r.

So instead of passing a directory name with a slash on end (which would instruct the command to copy a file into that directory preserving a file's name - the behaviour I expected), some more was added after the slash - an \r character, which led to the command accepting it as a new name for the file being copied.

1234ru

Posted 2016-10-24T08:45:22.267

Reputation: 81

0

You did not include the script or info on how you are running the script. I don't know if you are calling it from a cronjob or from a different user.

That said, the following very basic test script (t.sh) works perfectly for me on FreeBSD.

#!/bin/sh
echo "Pre test"
scp spider.goo:~/tColor.c ~/
echo "Post test"

Call like so:

sh ./t.sh

With the following output:

Pre test
Password for tigger@spider:
tColor.c       100% 1805     1.8KB/s   00:00    
Post test

Tigger

Posted 2016-10-24T08:45:22.267

Reputation: 136

I edited the question, clearing it up. Take a look. – 1234ru – 2016-10-26T14:42:14.393