5

I am trying to so something like this in my bashrc

SERVER=abc.com
geta() { scp ${SERVER}:$1 . ;}

SERVER=xyz.com
getx() { scp ${SERVER}:$1 . ;}

declare -f geta getx
geta () 
{ 
    scp ${SERVER}:$1 .
}
getx () 
{ 
    scp ${SERVER}:$1 .
}

What I want geta and getx to be set to is

geta () { scp abc.com:$1 . }
getx () { scp xyz.com:$1 . }

Is there a way to force variable expansion in function definitions?

Note: For clarification I changed the example

1
  • ping $SERVER isn't working for you? Commented Oct 31, 2012 at 3:56

3 Answers 3

5

You can use eval (escape the $ so that $1 doesn't get expanded)

SERVER=abc.com
eval "geta() { scp ${SERVER}:\$1 . ;}"
SERVER=xyz.com
eval "getx() { scp ${SERVER}:\$1 . ;}"

The output of declare -f geta getx

geta () 
{ 
    scp abc.com:$1 .
}
getx () 
{  
    scp xyz.com:$1 .
}
Sign up to request clarification or add additional context in comments.

1 Comment

bash: syntax error near unexpected token `('. eval "function geta() { scp ${SERVER}:\$1 . ;}" works, though.
1

This is a good time to use aliases:

get_file() { echo scp "$1":"$2" .; }

SERVER=abc.com
alias geta="get_file $SERVER"

SERVER=xyz.com
alias getx="get_file $SERVER"

geta foo
getx bar

outputs

scp abc.com:foo .
scp xyz.com:bar .

1 Comment

Almost what I need. I also have put_file() { scp $1 $SERVER:$2}. Can't figure out how to use your answer to accomplish that.
-1
pserver(){ 
    ping "$1"
}

then :

pserver abc.com

That should do the trick =)

Comments

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.