<!--
  canonical-url: https://www.avonture.be/blog/ssh-with-fuzzy-finder
  published:     2026-04-27
  This is a static plain-Markdown mirror generated at build time.
  Visit the canonical URL above for the fully rendered page, with images and interactive components.
-->

# Master your ssh command and select the host from a list

> Build an interactive, searchable SSH host selector using FZF. Learn to modularize your SSH configurations, add rich documentation, and trigger advanced custom actions via a fast Terminal User Interface.

---
![Master your ssh command and select the host from a list](/img/v2/sshf.webp)

**TL;DR**Managing dozens of server connections in a monolithic `~/.ssh/config` file quickly becomes unmaintainable and relies too heavily on memorization. This post demonstrates a cleaner approach by breaking your configuration into project-specific files within a `~/.ssh/conf.d/` directory, allowing you to attach rich, styled documentation directly above your host definitions. To tie it all together, you will implement a custom shell function (sshf) powered by FZF. This creates a fast, searchable Terminal User Interface (TUI) that lets you instantly filter hosts by name, project, or metadata. It also goes a step further by introducing custom keybindings, enabling you to trigger advanced contextual actions—like pinging servers, modifying configurations, or generating system inventories—directly from the search menu.

On my machine, I've accumulated more and more hosts in my `~/.ssh/config` file. While I can type `ssh server4` (see [zsh-ssh-config-suggestions](/blog/zsh-plugin-ssh-config-suggestions)) to jump to that server, I still have to remember the list of available servers. This is manageable when dealing with just a few, but I currently have around 50 servers, and relying solely on memory is no longer practical.

It would be much more convenient to view the full list of hosts through a TUI (*Terminal User Interface*), select the desired host, and simply press `Enter`. Furthermore, it would be extremely helpful to access contextual information—such as the URL hosted on that server, whether a database is running, the PHP version, and more.

Additionally, creating one `.conf` file per project would eliminate the need to maintain a massive, monolithic configuration file containing all 50 servers. Let's explore how to achieve this setup in this post.

*This builds on [Introduction to fzf - Fuzzy Finder](/blog/linux-fzf-introduction) and on the aliases created in [How to connect to your hosting server using SSH](/blog/connect-using-ssh-to-your-hosting-server). It applies to `~/.ssh/config` the same "one file per concern" philosophy as [Beyond the Monolith - Organizing Your ZSH Workflow Like a Pro](/blog/modular-zsh-workflow).*

Before diving into the technical details, here is a preview of the final result:

![Our sshf TUI](./images/tui.webp)

On the left side, there is a search box (allowing me to type `amazing` to filter on that pattern) above a list of hosts. On the right side, contextual information about the selected host is displayed.

Once a host is selected, I simply press `Enter` to open an SSH terminal session on that host—without having to enter my credentials manually.

Let's get started...

## Seeing It in Action with Docker

Before touching your own `~/.ssh/config`, try the whole TUI in a throwaway container — the exact
`amazing.conf`/`legacy.conf` files and the `sshf` function from further down are already in place.

> **Why Docker first?:**
>
> The Dockerfile below installs `fzf`, `perl` and `openssh-client`, writes the exact SSH config
> files shown further down, and appends the exact `sshf` function to `~/.bashrc`. Nothing on your
> own machine changes, and — since `1.2.3.4` and friends are the same placeholder IPs used
> throughout this article — pressing `Enter` on a host won't actually connect anywhere.

**Dockerfile**

```docker
FROM ubuntu:24.04

ENV DEBIAN_FRONTEND=noninteractive

# Ubuntu's docker image only enables "main" + "restricted" by default; fzf
# lives in "universe".
RUN sed -i 's/^Components: main restricted$/Components: main restricted universe multiverse/' \
        /etc/apt/sources.list.d/ubuntu.sources && \
    apt-get update && \
    apt-get install -y --no-install-recommends \
        fzf \
        perl \
        openssh-client && \
    rm -rf /var/lib/apt/lists/*

# ~/.ssh/conf.d/ — the two exact config files from this article
RUN mkdir -p /root/.ssh/conf.d && chmod 700 /root/.ssh

RUN printf '%s\n' \
    '# MyAmazingApp - Production Environment' \
    '#' \
    '# https://my.amazing_app.be' \
    '#     /var/www/amazing' \
    '#     pgsql: host=1.2.3.4 port=5438 dbname=amazing username=christophe' \
    '#' \
    '# <yellow>Backend:</yellow> PHP 8.5' \
    '# <green>Note:</green>    Part of TremendousApp.' \
    '#' \
    '# <bg-red>  CRITICAL  </bg-red> - This is a production server!' \
    '# <bg-yellow>    INFO    </bg-yellow> - Database is <green>PostgreSQL</green>' \
    'Host MyAmazingApp_PROD' \
    '    Hostname 1.2.3.4' \
    '    User usr_app_prod' \
    '' \
    '# MyAmazingApp - Tests Environment' \
    '#' \
    '# https://my.tests_amazing_app.be' \
    '#     /var/www/tests_amazing' \
    '#     pgsql: host=1.2.3.4 port=5438 dbname=amazing_newx username=christophe' \
    '#' \
    '# <yellow>Backend:</yellow> PHP 8.3' \
    '# <green>Note:</green> This is the TESTS environment' \
    '#' \
    '# <bg-yellow>    INFO    </bg-yellow> - Database is <green>PostgreSQL</green>' \
    'Host MyAmazingApp_TEST' \
    '    Hostname 6.7.8.9' \
    '    User usr_app_test' \
    '' \
    'Host YourAmazingApp' \
    '    Hostname 1.2.3.4' \
    '    User you' \
    > /root/.ssh/conf.d/amazing.conf

RUN printf '%s\n' \
    'Host LegacyApp' \
    '    Hostname 1.2.3.4' \
    '    User legacy' \
    > /root/.ssh/conf.d/legacy.conf


# ~/.ssh/config — includes both conf.d files
RUN printf '%s\n' \
    'Include conf.d/amazing.conf' \
    'Include conf.d/legacy.conf' \
    > /root/.ssh/config && \
    chmod 600 /root/.ssh/config /root/.ssh/conf.d/*.conf

# ~/.bashrc — the exact sshf() function from this article
RUN printf '%s\n' \
    '# ------------------------------------------------------------------------------' \
    '# FUNCTION: sshf' \
    '#' \
    '# DESCRIPTION:' \
    '#   An interactive SSH launcher using fzf and Perl. It parses SSH configuration' \
    '#   files (~/.ssh/config and ~/.ssh/conf.d/*.conf) to present a searchable' \
    '#   list of aliases. It supports multi-line comments and rich-text' \
    '#   formatting (colors, backgrounds) in the preview pane.' \
    '#' \
    '# FEATURES:' \
    '#   - Deep search: Filters by Alias, HostName, or any word in the comments.' \
    '#   - ANSI Support: Supports tags like <red>, <bg-red>, <bold>, etc.' \
    '#   - Non-cluttered UI: Keeps the list clean while showing full docs on the right.' \
    '#   - Robust Parsing: Handles complex multi-line SSH comment blocks.' \
    '#' \
    '# INSTALLATION:' \
    '#   1. Save this file as ~/.zsh/sshf.zsh' \
    '#   2. Add the following line to your ~/.zshrc:' \
    '#           [[ -f ~/.zsh/sshf.zsh ]] && source ~/.zsh/sshf.zsh' \
    '#   3. Restart your terminal or run: source ~/.zshrc' \
    '#' \
    '# USAGE:' \
    '#   $ sshf             # Opens interactive list' \
    '#   $ sshf query       # Opens interactive list pre-filtered by "query"' \
    '#' \
    '# DOCUMENTATION TAGS (Use in SSH config comments):' \
    '#   <red>text</red>, <green>text</green>, <yellow>text</yellow>, <blue>text</blue>' \
    '#   <bg-red>highlight</bg-red>, <bg-yellow>warning</bg-yellow>, <bold>important</bold>' \
    '# ------------------------------------------------------------------------------' \
    'sshf() {' \
    '    local selected' \
    '    # Step 1: Data extraction with Perl' \
    '    # Aggregates comments and attaches them to the subsequent Host definition.' \
    '    selected=$(cat ~/.ssh/config ~/.ssh/conf.d/*.conf 2>/dev/null | perl -ne '\''' \
    '        BEGIN { $sep = " ;; "; }' \
    '        s/\r//g; chomp;' \
    '' \
    '        # Capture comment lines' \
    '        if (/^\s*#/) {' \
    '            s/^\s*#\s?//;' \
    '            s/\|/-/;' \
    '            $buf .= ($buf eq "" ? "" : $sep) . $_;' \
    '            next;' \
    '        }' \
    '' \
    '        # Match Host alias (ignoring wildcards)' \
    '        if (/^\s*Host\s+([^*\s]+)/i) {' \
    '            $new_h = $1;' \
    '            if ($h) { print_line($h, $ip, $d); }' \
    '            $h = $new_h; $d = $buf; $buf = ""; $ip = "N/A";' \
    '            next;' \
    '        }' \
    '' \
    '        # Capture HostName/IP' \
    '        if (/^\s*HostName\s+(.+)/i) { $ip = $1; }' \
    '' \
    '        # Flush the last entry' \
    '        END { if ($h) { print_line($h, $ip, $d); } }' \
    '' \
    '        sub print_line {' \
    '            my ($h, $i, $d) = @_;' \
    '            $d = "No description" unless $d;' \
    '            # 150-space padding prevents description spillover in the main list' \
    '            my $padding = " " x 150;' \
    '            printf "%-20s | %-15s %s ##### %s\n", $h, $i, $padding, $d;' \
    '        }' \
    '    '\'' | \' \
    '    fzf --query="$1" \' \
    '        --reverse \' \
    '        --delimiter="#####" \' \
    '        --no-hscroll \' \
    '        --exact \' \
    '        --ansi \' \
    '        --header="ALIAS                | HOSTNAME" \' \
    '        --prompt="Search > " \' \
    '        --preview-window="right:70%:wrap" \' \
    '        --preview="echo {2} | perl -pe '\''' \
    '            s/ ;; /\n/g;' \
    '            s/<red>/\e[31m/g;          s/<\/red>/\e[0m/g;' \
    '            s/<green>/\e[32m/g;        s/<\/green>/\e[0m/g;' \
    '            s/<yellow>/\e[33m/g;       s/<\/yellow>/\e[0m/g;' \
    '            s/<bg-red>/\e[41;37m/g;    s/<\/bg-red>/\e[0m/g;' \
    '            s/<bg-yellow>/\e[43;30m/g; s/<\/bg-yellow>/\e[0m/g;' \
    '            s/<bold>/\e[1m/g;          s/<\/bold>/\e[0m/g;' \
    '        '\''" | \' \
    '    awk '\''{print $1}'\'')' \
    '' \
    '    # Step 2: Establish SSH Connection' \
    '    if [ -n "$selected" ]; then' \
    '        # Use ssh -G to get the computed values for this alias' \
    '        local ssh_info=$(ssh -G "$selected")' \
    '        local real_user=$(echo "$ssh_info" | awk '\''/^user / {print $2}'\'')' \
    '        local real_host=$(echo "$ssh_info" | awk '\''/^hostname / {print $2}'\'')' \
    '        local real_key=$(echo "$ssh_info" | awk '\''/^identityfile / {print $2}'\'' | head -n 1)' \
    '' \
    '        # Print the fully expanded command in bold cyan' \
    '        printf "\n\e[1;36m>> Executing: ssh -i %s %s@%s\e[0m\n\n" "$real_key" "$real_user" "$real_host"' \
    '' \
    '        ssh "$selected"' \
    '    fi' \
    '}' \
    >> /root/.bashrc

WORKDIR /root

# Signal clearly that this shell runs inside a container
RUN echo "PS1='\n\e[0;33m🐳 \e[0;36m\$(whoami)\e[0m \w # '" >> /root/.bashrc

CMD ["/bin/bash", "-i"]
```

Build and run it:

```bash
$ docker build -t sshf-demo .
[+] Building 26.4s (8/8) FINISHED
✔ exporting to image
$ docker run --rm -it sshf-demo
🐳 root ~ # sshf
```

The same TUI from the screenshot at the top of this article opens, listing all four hosts across
both `conf.d` files with their doc-blocks. Type `prod` or `php` to filter, exactly like the
"Using filtering options" section below — no real server is ever contacted.

## Install FZF

Check out my previous [Fuzzy Finder](/blog/linux-fzf-introduction) blog post if you need more detailed information. Otherwise, simply run the command below and complete the installation by answering "Yes" to all prompts, following the instructions displayed in your terminal.

```bash
$ git clone --depth 1 https://github.com/junegunn/fzf.git ~/.fzf ; ~/.fzf/install
```

While this isn't strictly related to SSH, you can now press `CTRL`+`R` to enjoy much easier access to your console history. This is just one of the great features of FZF.

## SSH configuration

The goal here is to organize your configuration more intelligently. Let's create an `~/.ssh/conf.d` folder where your configuration files will reside.

```bash
$ mkdir -p ~/.ssh/conf.d
```

For instance, create an `~/.ssh/conf.d/amazing.conf` file with the following content:

**amazing.conf**

```conf
# MyAmazingApp - Production Environment
#
# https://my.amazing_app.be
#     /var/www/amazing
#     pgsql: host=1.2.3.4 port=5438 dbname=amazing username=christophe
#
# <yellow>Backend:</yellow> PHP 8.5
# <green>Note:</green>    Part of TremendousApp.
#
# <bg-red>  CRITICAL  </bg-red> - This is a production server!
# <bg-yellow>    INFO    </bg-yellow> - Database is <green>PostgreSQL</green>
Host MyAmazingApp_PROD
    Hostname 1.2.3.4
    User usr_app_prod

# MyAmazingApp - Tests Environment
#
# https://my.tests_amazing_app.be
#     /var/www/tests_amazing
#     pgsql: host=1.2.3.4 port=5438 dbname=amazing_newx username=christophe
#
# <yellow>Backend:</yellow> PHP 8.3
# <green>Note:</green> This is the TESTS environment
#
# <bg-yellow>    INFO    </bg-yellow> - Database is <green>PostgreSQL</green>
Host MyAmazingApp_TEST
    Hostname 6.7.8.9
    User usr_app_test

Host YourAmazingApp
    Hostname 1.2.3.4
    User you
```

Then, create a second file named `~/.ssh/conf.d/legacy.conf` with this content:

**legacy.conf**

```conf
Host LegacyApp
    Hostname 1.2.3.4
    User legacy
```

Now, update your main `~/.ssh/config` file to include these new files:

```conf
Include conf.d/amazing.conf
Include conf.d/legacy.conf
```

This approach simply allows you to group hosts by project, making them easier to manage.

### Look at the amazing.conf file

We've defined three `Host` entries: `MyAmazingApp_PROD`, `MyAmazingApp_TEST`, and `YourAmazingApp`.

Notice that we've added some comments immediately before the first two `Host` lines (the placement is crucial).

This "doc-block" is plain text, so you can write whatever you like. For convenience, it supports markers like `blue`, `green`, `red`, `yellow`, `bg-red`, `bg-yellow`, and `bold`.

When the `MyAmazingApp_PROD` host is selected in the TUI, its associated doc-block will be displayed automatically.

## Add the sshf function

`sshf` gets its own file, in a folder your shell loads at startup (the organisation explained in [Beyond the Monolith](/blog/modular-zsh-workflow)): your rc file stays short, and removing the tool is deleting one file.

**sshf.sh**

```bash
# ------------------------------------------------------------------------------
# FUNCTION: sshf
#
# DESCRIPTION:
#   An interactive SSH launcher using fzf and Perl. It parses SSH configuration
#   files (~/.ssh/config and ~/.ssh/conf.d/*.conf) to present a searchable
#   list of aliases. It supports multi-line comments and rich-text
#   formatting (colors, backgrounds) in the preview pane.
#
# FEATURES:
#   - Deep search: Filters by Alias, HostName, or any word in the comments.
#   - ANSI Support: Supports tags like <red>, <bg-red>, <bold>, etc.
#   - Non-cluttered UI: Keeps the list clean while showing full docs on the right.
#   - Robust Parsing: Handles complex multi-line SSH comment blocks.
#
# INSTALLATION (zsh and bash, same code):
#   1. Save this file as ~/.zsh/fns/sshf.zsh (zsh) or ~/.bash/fns/sshf.sh (bash)
#   2. Load that folder from ~/.zshrc or ~/.bashrc with a "for fn_file ..." loop
#      (see https://www.avonture.be/blog/ssh-with-fuzzy-finder)
#   3. Open a new terminal
#
# USAGE:
#   $ sshf             # Opens interactive list
#   $ sshf query       # Opens interactive list pre-filtered by "query"
#
# DOCUMENTATION TAGS (Use in SSH config comments):
#   <red>text</red>, <green>text</green>, <yellow>text</yellow>, <blue>text</blue>
#   <bg-red>highlight</bg-red>, <bg-yellow>warning</bg-yellow>, <bold>important</bold>
# ------------------------------------------------------------------------------
sshf() {
    local selected
    # Step 1: Data extraction with Perl
    # Aggregates comments and attaches them to the subsequent Host definition.
    selected=$(cat ~/.ssh/config ~/.ssh/conf.d/*.conf 2>/dev/null | perl -ne '
        BEGIN { $sep = " ;; "; }
        s/\r//g; chomp;

        # Capture comment lines
        if (/^\s*#/) {
            s/^\s*#\s?//;
            s/\|/-/;
            $buf .= ($buf eq "" ? "" : $sep) . $_;
            next;
        }

        # Match Host alias (ignoring wildcards)
        if (/^\s*Host\s+([^*\s]+)/i) {
            $new_h = $1;
            if ($h) { print_line($h, $ip, $d); }
            $h = $new_h; $d = $buf; $buf = ""; $ip = "N/A";
            next;
        }

        # Capture HostName/IP
        if (/^\s*HostName\s+(.+)/i) { $ip = $1; }

        # Flush the last entry
        END { if ($h) { print_line($h, $ip, $d); } }

        sub print_line {
            my ($h, $i, $d) = @_;
            $d = "No description" unless $d;
            # 150-space padding prevents description spillover in the main list
            my $padding = " " x 150;
            printf "%-20s | %-15s %s ##### %s\n", $h, $i, $padding, $d;
        }
    ' | \
    fzf --query="$1" \
        --reverse \
        --delimiter="#####" \
        --no-hscroll \
        --exact \
        --ansi \
        --header="ALIAS                | HOSTNAME" \
        --prompt="Search > " \
        --preview-window="right:70%:wrap" \
        --preview="echo {2} | perl -pe '
            s/ ;; /\n/g;
            s/<red>/\e[31m/g;          s/<\/red>/\e[0m/g;
            s/<green>/\e[32m/g;        s/<\/green>/\e[0m/g;
            s/<yellow>/\e[33m/g;       s/<\/yellow>/\e[0m/g;
            s/<bg-red>/\e[41;37m/g;    s/<\/bg-red>/\e[0m/g;
            s/<bg-yellow>/\e[43;30m/g; s/<\/bg-yellow>/\e[0m/g;
            s/<bold>/\e[1m/g;          s/<\/bold>/\e[0m/g;
        '" | \
    awk '{print $1}')

    # Step 2: Establish SSH Connection
    if [ -n "$selected" ]; then
        # Use ssh -G to get the computed values for this alias
        local ssh_info=$(ssh -G "$selected")
        local real_user=$(echo "$ssh_info" | awk '/^user / {print $2}')
        local real_host=$(echo "$ssh_info" | awk '/^hostname / {print $2}')
        local real_key=$(echo "$ssh_info" | awk '/^identityfile / {print $2}' | head -n 1)

        # Print the fully expanded command in bold cyan
        printf "\n\e[1;36m>> Executing: ssh -i %s %s@%s\e[0m\n\n" "$real_key" "$real_user" "$real_host"

        ssh "$selected"
    fi
}
```

The code is the same for zsh and bash; only the folder and the loader differ.

**1. Create the file** in `~/.zsh/fns/`:

**Project: \~/.zsh/fns**

**sshf.zsh**

```bash
# ------------------------------------------------------------------------------
# FUNCTION: sshf
#
# DESCRIPTION:
#   An interactive SSH launcher using fzf and Perl. It parses SSH configuration
#   files (~/.ssh/config and ~/.ssh/conf.d/*.conf) to present a searchable
#   list of aliases. It supports multi-line comments and rich-text
#   formatting (colors, backgrounds) in the preview pane.
#
# FEATURES:
#   - Deep search: Filters by Alias, HostName, or any word in the comments.
#   - ANSI Support: Supports tags like <red>, <bg-red>, <bold>, etc.
#   - Non-cluttered UI: Keeps the list clean while showing full docs on the right.
#   - Robust Parsing: Handles complex multi-line SSH comment blocks.
#
# INSTALLATION (zsh and bash, same code):
#   1. Save this file as ~/.zsh/fns/sshf.zsh (zsh) or ~/.bash/fns/sshf.sh (bash)
#   2. Load that folder from ~/.zshrc or ~/.bashrc with a "for fn_file ..." loop
#      (see https://www.avonture.be/blog/ssh-with-fuzzy-finder)
#   3. Open a new terminal
#
# USAGE:
#   $ sshf             # Opens interactive list
#   $ sshf query       # Opens interactive list pre-filtered by "query"
#
# DOCUMENTATION TAGS (Use in SSH config comments):
#   <red>text</red>, <green>text</green>, <yellow>text</yellow>, <blue>text</blue>
#   <bg-red>highlight</bg-red>, <bg-yellow>warning</bg-yellow>, <bold>important</bold>
# ------------------------------------------------------------------------------
sshf() {
    local selected
    # Step 1: Data extraction with Perl
    # Aggregates comments and attaches them to the subsequent Host definition.
    selected=$(cat ~/.ssh/config ~/.ssh/conf.d/*.conf 2>/dev/null | perl -ne '
        BEGIN { $sep = " ;; "; }
        s/\r//g; chomp;

        # Capture comment lines
        if (/^\s*#/) {
            s/^\s*#\s?//;
            s/\|/-/;
            $buf .= ($buf eq "" ? "" : $sep) . $_;
            next;
        }

        # Match Host alias (ignoring wildcards)
        if (/^\s*Host\s+([^*\s]+)/i) {
            $new_h = $1;
            if ($h) { print_line($h, $ip, $d); }
            $h = $new_h; $d = $buf; $buf = ""; $ip = "N/A";
            next;
        }

        # Capture HostName/IP
        if (/^\s*HostName\s+(.+)/i) { $ip = $1; }

        # Flush the last entry
        END { if ($h) { print_line($h, $ip, $d); } }

        sub print_line {
            my ($h, $i, $d) = @_;
            $d = "No description" unless $d;
            # 150-space padding prevents description spillover in the main list
            my $padding = " " x 150;
            printf "%-20s | %-15s %s ##### %s\n", $h, $i, $padding, $d;
        }
    ' | \
    fzf --query="$1" \
        --reverse \
        --delimiter="#####" \
        --no-hscroll \
        --exact \
        --ansi \
        --header="ALIAS                | HOSTNAME" \
        --prompt="Search > " \
        --preview-window="right:70%:wrap" \
        --preview="echo {2} | perl -pe '
            s/ ;; /\n/g;
            s/<red>/\e[31m/g;          s/<\/red>/\e[0m/g;
            s/<green>/\e[32m/g;        s/<\/green>/\e[0m/g;
            s/<yellow>/\e[33m/g;       s/<\/yellow>/\e[0m/g;
            s/<bg-red>/\e[41;37m/g;    s/<\/bg-red>/\e[0m/g;
            s/<bg-yellow>/\e[43;30m/g; s/<\/bg-yellow>/\e[0m/g;
            s/<bold>/\e[1m/g;          s/<\/bold>/\e[0m/g;
        '" | \
    awk '{print $1}')

    # Step 2: Establish SSH Connection
    if [ -n "$selected" ]; then
        # Use ssh -G to get the computed values for this alias
        local ssh_info=$(ssh -G "$selected")
        local real_user=$(echo "$ssh_info" | awk '/^user / {print $2}')
        local real_host=$(echo "$ssh_info" | awk '/^hostname / {print $2}')
        local real_key=$(echo "$ssh_info" | awk '/^identityfile / {print $2}' | head -n 1)

        # Print the fully expanded command in bold cyan
        printf "\n\e[1;36m>> Executing: ssh -i %s %s@%s\e[0m\n\n" "$real_key" "$real_user" "$real_host"

        ssh "$selected"
    fi
}
```

**2. Load the folder from `~/.zshrc`.** Already done if you followed one of my ["Ollama daily use"](/series/ollama-daily-use) articles. Otherwise, add at the end of `~/.zshrc`:

```zsh title="~/.zshrc"
for fn_file in ~/.zsh/fns/*.zsh; do
  source "$fn_file"
done
```

**3. Open a new terminal** (or run `exec zsh`).

**1. Create the file** in `~/.bash/fns/`:

**Project: \~/.bash/fns**

**sshf.sh**

```bash
# ------------------------------------------------------------------------------
# FUNCTION: sshf
#
# DESCRIPTION:
#   An interactive SSH launcher using fzf and Perl. It parses SSH configuration
#   files (~/.ssh/config and ~/.ssh/conf.d/*.conf) to present a searchable
#   list of aliases. It supports multi-line comments and rich-text
#   formatting (colors, backgrounds) in the preview pane.
#
# FEATURES:
#   - Deep search: Filters by Alias, HostName, or any word in the comments.
#   - ANSI Support: Supports tags like <red>, <bg-red>, <bold>, etc.
#   - Non-cluttered UI: Keeps the list clean while showing full docs on the right.
#   - Robust Parsing: Handles complex multi-line SSH comment blocks.
#
# INSTALLATION (zsh and bash, same code):
#   1. Save this file as ~/.zsh/fns/sshf.zsh (zsh) or ~/.bash/fns/sshf.sh (bash)
#   2. Load that folder from ~/.zshrc or ~/.bashrc with a "for fn_file ..." loop
#      (see https://www.avonture.be/blog/ssh-with-fuzzy-finder)
#   3. Open a new terminal
#
# USAGE:
#   $ sshf             # Opens interactive list
#   $ sshf query       # Opens interactive list pre-filtered by "query"
#
# DOCUMENTATION TAGS (Use in SSH config comments):
#   <red>text</red>, <green>text</green>, <yellow>text</yellow>, <blue>text</blue>
#   <bg-red>highlight</bg-red>, <bg-yellow>warning</bg-yellow>, <bold>important</bold>
# ------------------------------------------------------------------------------
sshf() {
    local selected
    # Step 1: Data extraction with Perl
    # Aggregates comments and attaches them to the subsequent Host definition.
    selected=$(cat ~/.ssh/config ~/.ssh/conf.d/*.conf 2>/dev/null | perl -ne '
        BEGIN { $sep = " ;; "; }
        s/\r//g; chomp;

        # Capture comment lines
        if (/^\s*#/) {
            s/^\s*#\s?//;
            s/\|/-/;
            $buf .= ($buf eq "" ? "" : $sep) . $_;
            next;
        }

        # Match Host alias (ignoring wildcards)
        if (/^\s*Host\s+([^*\s]+)/i) {
            $new_h = $1;
            if ($h) { print_line($h, $ip, $d); }
            $h = $new_h; $d = $buf; $buf = ""; $ip = "N/A";
            next;
        }

        # Capture HostName/IP
        if (/^\s*HostName\s+(.+)/i) { $ip = $1; }

        # Flush the last entry
        END { if ($h) { print_line($h, $ip, $d); } }

        sub print_line {
            my ($h, $i, $d) = @_;
            $d = "No description" unless $d;
            # 150-space padding prevents description spillover in the main list
            my $padding = " " x 150;
            printf "%-20s | %-15s %s ##### %s\n", $h, $i, $padding, $d;
        }
    ' | \
    fzf --query="$1" \
        --reverse \
        --delimiter="#####" \
        --no-hscroll \
        --exact \
        --ansi \
        --header="ALIAS                | HOSTNAME" \
        --prompt="Search > " \
        --preview-window="right:70%:wrap" \
        --preview="echo {2} | perl -pe '
            s/ ;; /\n/g;
            s/<red>/\e[31m/g;          s/<\/red>/\e[0m/g;
            s/<green>/\e[32m/g;        s/<\/green>/\e[0m/g;
            s/<yellow>/\e[33m/g;       s/<\/yellow>/\e[0m/g;
            s/<bg-red>/\e[41;37m/g;    s/<\/bg-red>/\e[0m/g;
            s/<bg-yellow>/\e[43;30m/g; s/<\/bg-yellow>/\e[0m/g;
            s/<bold>/\e[1m/g;          s/<\/bold>/\e[0m/g;
        '" | \
    awk '{print $1}')

    # Step 2: Establish SSH Connection
    if [ -n "$selected" ]; then
        # Use ssh -G to get the computed values for this alias
        local ssh_info=$(ssh -G "$selected")
        local real_user=$(echo "$ssh_info" | awk '/^user / {print $2}')
        local real_host=$(echo "$ssh_info" | awk '/^hostname / {print $2}')
        local real_key=$(echo "$ssh_info" | awk '/^identityfile / {print $2}' | head -n 1)

        # Print the fully expanded command in bold cyan
        printf "\n\e[1;36m>> Executing: ssh -i %s %s@%s\e[0m\n\n" "$real_key" "$real_user" "$real_host"

        ssh "$selected"
    fi
}
```

**2. Load the folder from `~/.bashrc`.** Add at the end of `~/.bashrc` (the `-r` test keeps an empty folder from printing an error):

```bash title="~/.bashrc"
for fn_file in ~/.bash/fns/*.sh; do
  [[ -r "$fn_file" ]] && source "$fn_file"
done
```

**3. Open a new terminal** (or run `exec bash`).

Check that the shell knows the function: `type sshf` must answer `sshf is a shell function`.

Return to your terminal, type `sshf`, and press `Enter`. The magic will now unfold.

You will see the complete list of defined hosts. By typing a few letters, you will instantly apply filters. For example, simply type `prod` to filter the list and show only production servers.

Easy, isn't it?

## Using filtering options

You can filter based on any pattern. For instance, if you type `php`:

![Filtering on PHP servers](./images/php.webp)

FZF searches across all available data, not just the hostnames.

## My real use case

At work, I've taken this well beyond simply displaying a list of hosts. FZF supports custom keybindings, which means you can assign actions to keys other than just `Enter`. You can define actions triggered by `CTRL`+`A`, `CTRL`+`I`, or even a single letter like `E`.

This is where it gets truly powerful!

| Shortcut   | Description                                                                                                                                                                                                      |
| ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Ctrl`+`A` | I’ve set up a secondary screen that displays a list of actions to execute on the selected host.                                                                                                                  |
| `Ctrl`+`I` | I run an inventory management script that scans all my hosts (or just the filtered ones) and generates a web page with an up-to-date inventory of installed software (such as PHP, Python, PostgreSQL versions). |
| `E`        | You could, for example, open an editor to directly modify the configuration file of the selected host.                                                                                                           |

```bash
# ------------------------------------------------------------------------------
# FUNCTION: sshf_actions
# DESCRIPTION: Internal router for specific host actions
# ------------------------------------------------------------------------------
sshf_actions() {
    local action_key=$1
    local target=$2
    [[ -z "$target" ]] && return

    case "$action_key" in
        ctrl-a)
            local cmd=$(echo -e "Ping\nCopy-ID\nEdit-Config" | fzf --reverse --header="Action for $target")
            case "$cmd" in
                Ping) ping $(ssh -G "$target" | awk '/^hostname / {print $2}') ;;
                Copy-ID) ssh-copy-id "$target" ;;
                Edit-Config) ${EDITOR:-vim} ~/.ssh/config ;;
            esac
            ;;
        ctrl-h)
            clear
            printf "\e[1;34m>> Raw configuration for: %s\e[0m\n" "$target"
            ssh -G "$target"
            printf "\n\e[1;30mPress any key to return to list...\e[0m"
            read -k 1 -s
            sshf ""
            ;;
    esac
}

# ------------------------------------------------------------------------------
# FUNCTION: sshf
#
# DESCRIPTION:
#   An interactive SSH launcher using fzf and Perl. It parses SSH configuration
#   files (~/.ssh/config and ~/.ssh/conf.d/*.conf) to present a searchable
#   list of aliases. It supports multi-line comments and rich-text
#   formatting (colors, backgrounds) in the preview pane.
#
# FEATURES:
#   - Deep search: Filters by Alias, HostName, or any word in the comments.
#   - ANSI Support: Supports tags like <red>, <bg-red>, <bold>, etc.
#   - Non-cluttered UI: Keeps the list clean while showing full docs on the right.
#   - Robust Parsing: Handles complex multi-line SSH comment blocks.
#   - Shortcuts: CTRL-A for Actions, CTRL-H for Details.
#
# INSTALLATION (zsh and bash, same code):
#   1. Save this file as ~/.zsh/fns/sshf.zsh (zsh) or ~/.bash/fns/sshf.sh (bash)
#   2. Load that folder from ~/.zshrc or ~/.bashrc with a "for fn_file ..." loop
#      (see https://www.avonture.be/blog/ssh-with-fuzzy-finder)
#   3. Open a new terminal
#
# USAGE:
#   $ sshf             # Opens interactive list
#   $ sshf query       # Opens interactive list pre-filtered by "query"
#
# DOCUMENTATION TAGS (Use in SSH config comments):
#   <red>text</red>, <green>text</green>, <yellow>text</yellow>, <blue>text</blue>
#   <bg-red>highlight</bg-red>, <bg-yellow>warning</bg-yellow>, <bold>important</bold>
# ------------------------------------------------------------------------------
sshf() {
    local out
    # Step 1: Data extraction with Perl
    # Aggregates comments and attaches them to the subsequent Host definition.
    out=$(cat ~/.ssh/config ~/.ssh/conf.d/*.conf 2>/dev/null | perl -ne '
        BEGIN { $sep = " ;; "; }
        s/\r//g; chomp;

        # Capture comment lines
        if (/^\s*#/) {
            s/^\s*#\s?//;
            s/\|/-/;
            $buf .= ($buf eq "" ? "" : $sep) . $_;
            next;
        }

        # Match Host alias (ignoring wildcards)
        if (/^\s*Host\s+([^*\s]+)/i) {
            $new_h = $1;
            if ($h) { print_line($h, $ip, $d); }
            $h = $new_h; $d = $buf; $buf = ""; $ip = "N/A";
            next;
        }

        # Capture HostName/IP
        if (/^\s*HostName\s+(.+)/i) { $ip = $1; }

        # Flush the last entry
        END { if ($h) { print_line($h, $ip, $d); } }

        sub print_line {
            my ($h, $i, $d) = @_;
            $d = "No description" unless $d;
            # 150-space padding prevents description spillover in the main list
            my $padding = " " x 150;
            printf "%-20s | %-15s %s ##### %s\n", $h, $i, $padding, $d;
        }
    ' | \
    fzf --query="$1" \
        --reverse \
        --delimiter="#####" \
        --no-hscroll \
        --exact \
        --ansi \
        --header="──────────────────────────────────────────────────────────────
ENTER  : Connect to host
CTRL-A : Open actions menu (Ping, MTR, etc.)
CTRL-H : Display raw SSH configuration
──────────────────────────────────────────────────────────────
ALIAS                | HOSTNAME" \
        --prompt="Search > " \
        --expect="ctrl-a,ctrl-h" \
        --preview-window="right:70%:wrap" \
        --preview="echo {2} | perl -pe '
            s/ ;; /\n/g;
            s/<red>/\e[31m/g;           s/<\/red>/\e[0m/g;
            s/<green>/\e[32m/g;         s/<\/green>/\e[0m/g;
            s/<yellow>/\e[33m/g;        s/<\/yellow>/\e[0m/g;
            s/<bg-red>/\e[41;37m/g;     s/<\/bg-red>/\e[0m/g;
            s/<bg-yellow>/\e[43;30m/g;  s/<\/bg-yellow>/\e[0m/g;
            s/<bold>/\e[1m/g;           s/<\/bold>/\e[0m/g;
        '")

    # fzf with --expect returns the key on the first line and the selection on the second
    local key=$(head -n1 <<< "$out")
    local selected_line=$(sed -n '2p' <<< "$out")
    local selected=$(echo "$selected_line" | awk '{print $1}')

    if [ -n "$key" ]; then
        # A shortcut was pressed
        sshf_actions "$key" "$selected"
    elif [ -n "$selected" ]; then
        # Step 2: Establish SSH Connection (Default Enter)
        local ssh_info=$(ssh -G "$selected")
        local real_user=$(echo "$ssh_info" | awk '/^user / {print $2}')
        local real_host=$(echo "$ssh_info" | awk '/^hostname / {print $2}')
        local real_key=$(echo "$ssh_info" | awk '/^identityfile / {print $2}' | head -n 1)

        printf "\n\e[1;36m>> Executing: ssh -i %s %s@%s\e[0m\n\n" "$real_key" "$real_user" "$real_host"

        ssh "$selected"
    fi
}
```

![Using Key bindings](./images/tui_with_actions.webp)

Your imagination is the only limit!
