问题
I want place a simple bash function in my .bashrc that wraps around the scp command by accepting a 'source' argument and 'destination' argument, and so far have tried both
function send() {
eval "scp $1 user@annoyingly-long-server-name:$2"
}
and
function send() {
scp $1 user@annoyingly-long-server-name:$2
}
...but when I call either of the above a la
send file.txt ~/
I get the error scp: home-directory-on-remote-machine: Operation not supported. After echoing each argument, it seems that the tilde is expanded into the remote machine's home directory before evaluation. How can I prevent this?
回答1:
First of all, you can use ssh-keys to prevent typing of passwords.
Before you use your function do just once:
ssh-copy-id remoteHostName
It is considered better to use keys instead of passwords for ssh and that is true for scp.
Second, you don't need eval.
function send() {
scp "$1" user@annoyingly-long-server-name:"$2"
}
And finally, you need to use explicit path names:
send foo /home/luke/foo
Because ~ is some how not properly evaluated to /home/luke/.
update, side story:
If your motivation for writing the function send is really that annoyingly-long-server-name you should know about /home/luke/.ssh/config.
Inside this file you can do wonders:
Host a-nicer-alias
Hostname stupid-host-name.verylongdoamin.com
User luke
Then you can simply do scp a-nicer-alias
回答2:
I figured out a way to convert back from the expanded tilde to the string ~ inside the function using this thread. The function is now
function send() {
dest="$2"
dest="${dest/#$HOME/\~}"
scp $1 user@annoyingly-long-server-name:$dest
}
In the second line, if the string "$HOME" appears at the start of the second argument, it is replaced by a tilde ~. If the source and destination have identical $HOMEs and the user actually did supply the destination path explicitly, it won't do any harm to convert to ~, but if they do not have identical $HOMEs, it fixes the problem.
For some reason it seemed that I had to assign $2 to a variable before performing the string replacement.
来源:https://stackoverflow.com/questions/45317559/issues-using-the-tilde-in-a-simple-function-wrapper-around-scp