0

While trying to write a script, I found an interesting issue with cat today. If I do the following at the command line, everything works properly:

var=$(ssh user@server "cat /directory/myfile.sh")
echo $var > ~/newfile.sh

This works and I have a script file with all the proper formatting and can run it. However, if I do the EXACT same thing in a script:

#!/bin/sh

var=$(ssh user@server "cat /directory/myfile.sh")
echo $var > ~/newfile.sh

The file is mangled with carriage returns and weird formatting.

Does anyone know why this is happening? My goal is to ultimately cat a script from a server and run it locally on my machine.

EDIT

I now know that this is happening because of my invoking #!/bin/sh in my shell script. The command line works because I'm using zsh and it is preserving the formatting.

Is there a way to cat back the results regardless of the shell?

Oded
  • 489,969
  • 99
  • 883
  • 1,009
nullByteMe
  • 6,141
  • 13
  • 62
  • 99
  • 1
    `/bin/sh` might be a different shell than the one you're running. In particular, on Debian and derivatives (Ubuntu, Mint), `/bin/sh` is the Debian Almquist Shell dash, not bash. – Fred Foo Jun 26 '13 at 19:35
  • @larsmans interesting... my native shell is `zsh` so do you think that could be the reason for the varying results? – nullByteMe Jun 26 '13 at 19:36
  • 1
    I've never used Zsh, but that's still my best guess. Check if `echo` is built-into Zsh. – Fred Foo Jun 26 '13 at 20:03
  • @larsmans it was in fact the difference in shells. If I change my shell to `bash` or `sh` I get the issues with formatting and since my shell was using `#!/bin/sh` it was throwing off the formatting. Is there any way to echo back the exact format of a file regardless of the shell being used? – nullByteMe Jun 26 '13 at 22:53
  • Try replacing `echo` with `/bin/echo`. – Fred Foo Jun 26 '13 at 23:02
  • If it works with `zsh`, use `/bin/zsh` in the shebang line? – Jonathan Leffler Jun 26 '13 at 23:03

1 Answers1

1

As you seem to have figured out, word splitting is off by default on zsh, but on in sh, bash, etc. You can prevent word splitting in all shells by quoting the variable:

echo "$var" > ~/newfile.sh

Note that echo appends a newline to its output by default, which you can suppress (on most echo implementations and builtins) with -n.

Kevin
  • 53,822
  • 15
  • 101
  • 132