Notes on Bash

Prevent Bash SSH completion from using hosts entries

By default, the completion helper for SSH from the Bash completion project populates the hostname suggestions with entries from the hosts file located at /etc/hosts. This may not be very convenient if you use the hosts file to block ads. In such a case there would be a very large number of entries in /etc/hosts, none of which would be a host you would want to SSH into.

The completion helper for SSH gets the host names from the _known_hosts_real utility function. To prevent this function from using /etc/hosts entries, set the environment variable BASH_COMPLETION_KNOWN_HOSTS_WITH_HOSTFILE to an empty value. However, note that older versions of _known_hosts_real used the environment variable COMP_KNOWN_HOSTS_WITH_HOSTFILE for the same purpose.

export COMP_KNOWN_HOSTS_WITH_HOSTFILE=
export BASH_COMPLETION_KNOWN_HOSTS_WITH_HOSTFILE=

cd with automatic sourcing of .env and .env.leave files

This is basically a leaner NIH implementation of autoenv. The below snippet (which should be put in an appropriate startup file, e.g., ~/.bashrc) makes a cd wrapper such that if you cd into a directory containing an .env file, it will automatically be sourced. Similarly, if the directory contains an .env.leave file, it will be sourced whenever the current directory is no longer a child directory of the root directory containing the .env file. (In this sense, my implementation is different from that of autoenv’s, which sources .env.leave as soon as you change the directory.) Of course, my implementation has security risks as any .env file that’s encountered is sourced. Nested environments, symlinked directories, etc., can also lead to unwanted behavior.

cd() {
    if builtin cd "$@"
    then
        if [[ -f ".env" ]] && [[ "$PWD" != "$AUTOENV_ROOT" ]]
        then
            source ".env"
            export AUTOENV_ROOT="$PWD"

            if [[ -f ".env.leave" ]]
            then
                export AUTOENV_LEAVE="$PWD/.env.leave"
            else
                unset -v AUTOENV_LEAVE
            fi
        fi

        # If there's an .env.leave file, and we're not in a child
        # directory of the directory containing the .env file, then
        # source the .env.leave file.
        if [[ "$AUTOENV_LEAVE" ]] && [[ "$PWD"/ != "$AUTOENV_ROOT"/* ]]
        then
            source "$AUTOENV_LEAVE"
            unset -v AUTOENV_ROOT AUTOENV_LEAVE
        fi

        return 0
    else
        return $?
    fi
}

Last updated: 2022-12-13 17:00 EST