Posts Tagged ‘stupid bash tricks’

Audible Bell in Terminal

Sunday, November 15th, 2009
echo -e "\a"

Extend bash functionality

Saturday, April 11th, 2009
# make bash autocomplete with up arrow
bind '"\e[A":history-search-backward'
bind '"\e[B":history-search-forward'

# make tab cycle through commands instead of listing
bind '"\t":menu-complete'

Intercepting "command not found" in bash

Friday, March 6th, 2009

On Debian, bash is patched with an interesting new function: command_not_found_handle. This intercepts exit code 127 ("command not found") and allows you to do neat things. Debian uses it to pass it through the apt database, letting you know if a command you tried to invoke is not available, but can be found in the apt repos, and how to install it. Pretty spiffy.

This, of course, can be modified. Where I work, we use numbers to identify servers. I have a script that grabs login credentials from our internal systems and auto-logs me into servers based on their number. For example, I'd run `connect 12345′ to connect to server 12345.

By adding the following to my .bashrc:

function command_not_found_handle {
    /home/kale/bin/command-not-found $1
}

And creating the following script, with regex in place to only care about numbers, placed in /home/kale/bin/command-not-found:

#!/bin/bash

MYBOOL=`echo $1 | awk '$1 ~ /^[0-9]+-*[0-9]*$/ {print $0}' | wc -l | awk '{print $1}'`

if [ "$MYBOOL" == "1″ ]; then
        /home/kale/bin/connect $1
else
        exit 127
fi

(where `connect' is the path to my connect script, previously written)

This now allows me to do this awesome deal:

kale@bastion:~$ 12345
Connecting to server 12345
root@12345:~#
 

If you didn't catch it, I don't need to specify a command — just the argument. As there's no application in my $PATH named `12345′, it falls through to the command_not_found_handle function, which then launches my connect script.

Who needs commands? I just saved hundreds of wasted seconds per night on typing "connect"!

Bash portscanner

Wednesday, March 4th, 2009

Well, why not?

HOST=127.0.0.1;for((port=1;port<=65535;++port));do echo -en "$port ";if echo -en "open $HOST $port\nlogout\quit" | telnet 2>/dev/null | grep 'Connected to' > /dev/null;then echo -en "\n\nport $port/tcp is open\n\n";fi;done