0

I am trying to create a simple bash script that takes paths to directories as input and plugs them into an scp command. The scp command looks like this:

scp user@server.com:/path/to/directory/on/server /path/to/directory/on/local/machine

I have made a simple bash function,

s2h () {
    local address_in_server="$1"
    local address_in_home="$2"
    echo "$address_in_server"
    echo "$address_in_home"
    scp user@server.com:$address_in_server $address_in_home
}

After running this script as s2h ~/testing/somefile.txt ~/Desktop The echo commands output

/Users/me/testing
/Users/me/Desktop/

This particular pathway, with /Users/me is meant for my local machine. The problem is that bash is interpreting the "~" for the server as the "~" for my local machine. If I enter

s2h /home/myusername/testing/somefile.txt ~/Desktop

It works perfectly.

However, the command

scp user@server.com:~/testing/somefile.txt ~/Desktop 

also works.

My question is, how do I get the bash script to understand what ~ means when calling a file from my server from an argument, and not translate it to the local meaning of ~?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
megamence
  • 335
  • 2
  • 10

1 Answers1

3

Use quotes to suppress local tilde expansion:

s2h "~/testing/somefile.txt" ~/Desktop
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • Thank you @Cyrus. This worked. Is there a way to do it in the bash function itself? want to make the user interface as simple as possible. i want it to work with ```s2h ~/testing/somefile.txt ~/Desktop``` – megamence Feb 07 '21 at 18:09
  • It might help to replace in your code `"$1"` with `"${1/#$HOME/\~}"` to get back your `~`. – Cyrus Feb 07 '21 at 18:16