Search code examples
bashsshscp

Unexpected ambiguous redirect in bash script if connecting through ssh to server itself


I execute scripts, for example one of them is below. It work property as I expected. The file will send to remote PC and all output of copying, include possible error will store in file with extension log.

#!/bin/bash
scp /tmp/v8_8PcnYL_41.sh evgeniy@Ubuntu-VM2:/tmp/v8_8PcnYL_44.sh >> "/tmp/v8_8PcnYL_42.log" 2>&1

But, it wont work if execution PC and ssh server is same PC. In this case i get a error ": ambigous redirect 1", BUT if i execute 2nd line just in the terminal there is no error and operation will execute as expected. So, why it happens? And what to do in this case?

Ubuntu 18.04, also 22.04

To better understanding here is console output:

evgeniy@Ubuntu-VM2:~$ sudo su usr1cv8
[sudo] Enter password for evgeniy:
$ cat /tmp/v8_8PcnYL_43.sh
#!/bin/bash
scp /tmp/v8_8PcnYL_41.sh evgeniy@Ubuntu-VM2:/tmp/v8_8PcnYL_44.sh >> "/tmp/v8_8PcnYL_42.log" 2>&1
$ ls -lha /tmp/v8_8PcnYL_43.sh
-rwxr-x--x 1 usr1cv8 grp1cv8 111 сен 28 20:34 /tmp/v8_8PcnYL_43.sh
$ bash /tmp/v8_8PcnYL_43.sh
: ambiguous redirect 1
$
$ scp /tmp/v8_8PcnYL_41.sh evgeniy@Ubuntu-VM2:/tmp/v8_8PcnYL_44.sh >> "/tmp/v8_8PcnYL_42.log" 2>&1
$ cat /tmp/v8_8PcnYL_42.log
$ exit
evgeniy@Ubuntu-VM2:~$ cat /tmp/v8_8PcnYL_44.sh
#!/bin/bash
cd ~/
/opt/mssql-tools/bin/sqlcmd -S CHECK -U sa -P [hidden] -h -1 -b -Q "SELECT name FROM master.dbo.sysdatabases"
exit $?
evgeniy@Ubuntu-VM2:~$

Solution

  • The script has DOS line endings. The big clue was the error message:

    : ambiguous redirect 1
    

    is missing the part that usually comes before the : identifying the tool producing the message and the string that is causing the error, e.g.:

    $ x='foo bar'
    $ echo stuff > $x
    bash: $x: ambiguous redirect
    
    $ echo stuff > $x$'\r'
    ': ambiguous redirect
    

    See Why does my tool output overwrite itself and how do I fix it? for more info on DOS line endings and how to fix them.