Shaun
Shaun

Reputation: 43

Creating bash aliases via .bashrc

As a sysadmin I routinely rdp and ssh into remote machines for administration.

I've created a file, ${SERVER_FILE}, containing one entry per line noting the hostname and protocol to use when connecting to a given server.

Example:

...
server1,ssh
winsrv,rdp
...

Given the above entries I want the following to be created+evaluated (rdp is itself a script on my system):

alias server1='ssh server1' winsrv='rdp winsrv'

The following code, when I cut and paste the resultant output to an alias command, works flawlessly:

$ echo $(sed "s/\(.*\),\(rdp\|ssh\)/\1='\2 \1' /g" ${SERVER_FILE} | tr -d '\n')
server1='ssh server1' winsrv='rdp winsrv'

$ alias server1='ssh server1' winsrv='rdp winsrv'

$ alias
alias server1='ssh server1'
alias winsrv='rdp winsrv'

SO I change it to this to actually cause the aliases to be created and I get errors:

$ alias $(sed "s/\(.*\),\(rdp\|ssh\)/\1='\2 \1' /g" ${SERVER_FILE} | tr -d '\n')
bash: alias: server1': not found
bash: alias: winsrv': not found

$ alias 
alias server1=''\''ssh'
alias winsrv=''\''rdp'

Advice?

Upvotes: 1

Views: 646

Answers (3)

Swiss
Swiss

Reputation: 5829

Might I suggest awk instead of sed for a much more easily readable command?

awk 'BEGIN { FS="," 
             format = "%s=\"%s %s\" " }
     $2 ~ /(rdp|ssh)/ { printf format, $1, $2, $1 }' ${SERVER_FILE}

Upvotes: 1

Chriszuma
Chriszuma

Reputation: 4557

Well, it looks like alias and echo are interpreting some backslashes differently. This is admittedly a hack, but I would try this:

alias $(echo $(sed "s/\(.*\),\(rdp\|ssh\)/\1='\2 \1' /g" ${SERVER_FILE} | tr -d '\n'))

:-)

Upvotes: 0

Burton Samograd
Burton Samograd

Reputation: 3638

Try:

 $ eval alias $(sed "s/\(.*\),\(rdp\|ssh\)/\1='\2 \1' /g" ${SERVER_FILE} | tr -d '\n')

Works for me.

Upvotes: 2

Related Questions