I made a little shell script, that parses the .ssh config and allows me to pick an entry with fzf, and then connects to that host:
#!/bin/bash
set -o nounset -o errexit -o pipefail
list_remote_hosts()
{
choice="$(cat $HOME/.ssh/config | awk -v RS= -v FS=\\n -v IGNORECASE=1 '
{
ip = ""
alias = ""
id_file = ""
username = ""
port = ""
for (j = 1; j <= NF; ++j) {
split($j, tmp, " ")
if (tmp[1] == "Host") { alias = tmp[2] }
if (tmp[1] == "Hostname") { ip = tmp[2] }
if (tmp[1] == "IdentityFile") { id_file = tmp[2] }
if (tmp[1] == "User") { username = tmp[2] }
if (tmp[1] == "Port") { port = tmp[2] }
}
if (ip || alias && alias != "*") {
if (port == "")
{
port = "22"
}
print "ssh " username "@" ip " -i " id_file " -p " port
}
}
' | fzf)"
"$($choice)"
}
list_remote_hosts
That works, but I am having problems giving ownership to the current shell. When connected, the script freezes (because ssh is started in a subshell I imagine). Once I type e.g. exit, and the ssh command terminates, I can see the output.
I want to automatically give ownership to the current shell when the script is run, so that I get the same behavior like running the ssh command from within my terminal.
I tried all sorts of things like appending && zsh
or using eval
or exec
, but none of these worked.
How can I do this?
ssh **<TAB>
with the default keybindings of fzf will already invoke fzf to select the host to connect to (github.com/junegunn/fzf#host-names).cat file | awk '...'
is functionally identical toawk '...' file
, except the shorter version is better code.cat file
is usually unnecessary