SCP doesn't work when echo in .bashrc?

Solution 1:

Using echo in a .bashrc will break scp, as scp expects to see its protocol data over the stdin/stdout channels. See https://bugzilla.redhat.com/show_bug.cgi?id=20527 for more discussion on this issue.

There's a few workarounds available:

  • Condition on the 'interactive' flag (e.g. case $- in *i* as suggested by tripleee)
  • Use the tty utility to detect an interactive shell (e.g. if tty > /dev/null or if [ -t 0 ])
  • Check the value of $SSH_TTY

I suppose you should use whichever one works for you. I don't know what the best (most portable/most reliable) option is, unfortunately.

Solution 2:

To add to nneonneo's options, you can also condition with the interactive flag with

if [[ $- =~ "i" ]]

which I think is possibly the clearest way in bash.

Solution 3:

This works for me,
In .bashrc add first line as:

if [ -z "$PS1" ]; then
    return
fi

https://superuser.com/questions/690735/can-i-tell-if-im-in-an-scp-session-in-my-bashrc

Solution 4:

The default Ubuntu .bashrc contains the following snippet which already takes care of the problem:

# If not running interactively, don't do anything
case $- in
    *i*) ;;
    *) return;;
esac