Running scp when .bashrc of remote machine includes source command

You should make part or all of your .bashrc not run when your shell is non-interactive. (An scp is an example of a non-interactive shell invocation, unless someone has radically altered your systems.) Then put all commands that can possibly generate output in that section of the file.

A standard way to do this in an init file is:

# Put all the commands here that should run regardless of whether
# this is an interactive or non-interactive shell.

# Example command:
umask 0027

# test if the prompt var is not set
if [ -z "$PS1" ]; then
    # prompt var is not set, so this is *not* an interactive shell
    return
fi

# If we reach this line of code, then the prompt var is set, so
# this is an interactive shell.

# Put all the commands here that should run only if this is an
# interactive shell.

# Example command:
echo "Welcome, ${USER}.  This is the ~/.bashrc file."

You might also see people use

[ -z "$PS1" ] && return

instead of my more verbose if statement.

If you don't want to rearrange your whole file, you can also just make certain lines run only in interactive context by wrapping them like so:

if [ -n "$PS1" ]; then
    echo "This line only runs in interactive mode."
fi

If you segregate your .bashrc this way, then your scp commands should no longer have this problem.

Tags:

Scp