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 [email protected]:/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 [email protected]:$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 [email protected]:~/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 ~?

2
  • Just invoke it like s2h testing/somefile.txt ~/Desktop -- the remote file will be found relative to your remote home directory. Commented Feb 7, 2021 at 15:35
  • hi @glennjackman. that did not work... Commented Feb 7, 2021 at 18:08

1 Answer 1

3

Use quotes to suppress local tilde expansion:

s2h "~/testing/somefile.txt" ~/Desktop
Sign up to request clarification or add additional context in comments.

2 Comments

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
It might help to replace in your code "$1" with "${1/#$HOME/\~}" to get back your ~.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.