0

I am using scp to copy a file from a server to my computer. The command works fine when I type it from the command line, but when I try to make a script to do it, it fails with a "cp: cannot stat" error. It seems like the script is trying to check for the existence of a directory on my computer, when I do not intend it to do so.

I have a variable $LOGIN which equals user@server

Here is the command that works on the command line:

scp $LOGIN:dir/dir/file.txt .

Here is what I have in the bash script:

scp "$LOGIN:$1 $2"

Here is how I call the script:

./scriptname dir/dir/file.txt .

And the error:

cp: cannot stat ':dir/dir/file.txt': No such file or directory

Any ideas on how to get this script to work?

  • 2
    Your quotes are incorrect. scp "$LOGIN:$1 $2" should be scp "$LOGIN:$1" "$2" – Philip Couling Feb 26 at 17:00
3

Because LOGIN was not exported as an environment variable, you lost it when you entered the script, so script tried to execute:

scp :dir/dir/file.txt .

instead of your desired:

scp user@server::dir/dir/file.txt .

The shortest "fix" would be to:

export LOGIN

before executing the script.

Note also that the quoting would be better as:

scp "$LOGIN":"$1" "$2"

so that scp sees two independent strings, not one.

  • Thanks Jeff that was it. I didn't realize scripts didn't have access to the bash environment variables. That is weird. – matthew foreman Feb 26 at 17:10
  • there's a fine distinction between a shell variable and an environment variable – Jeff Schaller Feb 26 at 17:11
  • do take care with your variable names, too. People have been bitten using PATH, and there are others that are readonly or would change bash behavior in unexpected ways. Consider using lower-case variable names for your own data/purposes. – Jeff Schaller Feb 26 at 17:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.