Home > Net >  Chaining commands together in .bashrc
Chaining commands together in .bashrc

Time:07-17

I'm trying to chain two commands together in a function or alias. What I want to do is ssh into a proxy box, and then into another box from there. So something like:

ssh -J mylogin@host mylogin@host2

So far i've tried:

function doot {ssh -J mylogin@host && mylogin@"$1"}

and:

function doot {ssh -J mylogin@host; mylogin@"$1"}

and:

alias doot="ssh -J mylogin@host; mylogin@"$1""

It either doesn't recognize the function, or the alias just gives me an error. I feel that it's having an issue with the "$1" but i'm not sure how to chain these two commands together.

I want to just type in doot [nameofhost] and execute the command

ssh -J mylogin@host mylogin@host2

CodePudding user response:

Neither of your attempted functions or alias do ssh -J mylogin@host mylogin@host2. Why?

The use of && and ';' separate commands. In your case that would make two separate commands out of ssh -J mylogin@host and mylogin@"$1". You need a single command specifying mylogin@host as the jump-host and mylogin@"$1" as the final destination. Simply do:

doot() { 
  ssh -J mylogin@host mylogin@"$1"
}

(note: quotes are not wrong but not entirely needed as hostnames don't contain whitespace. Also note "$1" within the function refers to the function argument, not the command line argument for your script. You would need to call as doot "$1". There is no ';' or && involved.)

There is a problem with alias as an alias does not contain arguments. From man bash:

There is no mechanism for using arguments in the replacement text.
If arguments are needed, a shell function should be used (see FUNCTIONS below).

Also, you want to validate that $1 has been given. You can do that with:

[ -z "$1" ] && {  ## validate at least one argument given
  printf "error: destination hostname required as argument.\n" >&2
  return 1
}

(note: if you are calling the function that includes this test from the command line in the parent shell, your function should return instead of exit. In that case exit would exit the parent shell. If you use the function within a separate script you call from the parent, then you want exit to close the subshell)

CodePudding user response:

You did not specify if the proxy required any additional parameters, sssuming it just a jump box, allowing ssh

Function foo { 
    ssh mylogin@host ssh mylogin@host2
}

If your current user is ‘mylogin’, you can abbreviate to

ssh host ssh host2
  •  Tags:  
  • bash
  • Related