bash builtins

Bash
Image via Wikipedia

This post will be fully dedicated to stuff you can do from with in bash, as opposed to invoking external programs to do the job.

$ help :

:: :

    No effect; the command does nothing.

    A zero exit code is returned.

This are two interesting bits here, first one is the shell builtin "help". Bash apparently doesn't believe in individual man pages and documents it's stuff in either hugh man bash, "help" pages or not at all (hey completion!). The second interesting part is the :, as you can see it does nothing. Why does it exist? Well, to start with it was defined in a standard. To be honest it can be useful, for example to create a cool looking infinite loops:

while :; do ....; done

Suppose you would like a quick and generic way to have a paginated display of some string in your current directory. A naive way would be:

$ alias cmd='grep -r "$1" . | less'

$ cmd string

string: No such file or directory

The problem here is that alias is nothing more than a dumb text expansion, the only thing it does is expand the cmd to grep -r "$1" . | less. So the cmd string is exactly the same as:

$ grep -r "$1" . | less string

string: No such file or directory

The reason why we get the error is that less treats any argument as a file to open, since i don't have a "string" file it fails. So what is a solution if you want to insert an argument in the middle of pipeline? An ugly way would be to create a script, a cool way would be to create a function. Functions in bash can take arguments and are full blown composite commands. The final solution would be something ala:

cmd(){ grep -r "$1" . | less; }
Ever wanted to do regex straight out bash? Since bash3 with the =~ operator you can. The result is stored in BASH_REMATCH array, first element is the entire string regex matched, the others are stored back references.
$ [[ caab =~ [^a]*(a+).* ]] && printf "\

entire string matched: ${BASH_REMATCH[0]}

first back reference: ${BASH_REMATCH[1]}\n"

entire string matched: caab

first back reference: aa
blog comments powered by Disqus