DLAN ARAPS

BASH IS WEIRD - 5 THINGS

This blog post is a list of weird or unknown bash features I’ve come across in my travels. Some of these may not be that practical but they’re cool nonetheless.

1. Bypassing shell aliases.

You can bypass a shell alias by adding a leading \ to the command. This can be used as a simpler alternative to command ls.

For example: If I have an alias for ls that uses --color=auto, I can bypass it by running \ls.

# alias
ls

# command
\ls

2. Reversing an array.

It’s possible to reverse an array in bash without using any external programs or looping by making use of extdebug.

When extdebug is enabled the array BASH_ARGV is made available and it contains the function’s arguments in reverse order.

reverse_array() {
    # Reverse an array.
    # Usage: reverse_array "array"

    shopt -s extdebug
    f(){ printf "%s " "${BASH_ARGV[@]}"; }; f "$@"
    shopt -u extdebug

    printf "\\n"
}

3. Use printf as an alternative to date.

The printf command in bash has direct support for strftime and can be used as a lighter alternative to the date command as it doesn’t spawn an external process.

# Using date.
date "+%a %d %b  - %l:%M %p"

# Using printf.
printf "%(%a %d %b  - %l:%M %p)T\\n"

# Assigning a variable.
printf -v date "%(%a %d %b  - %l:%M %p)T\\n"

4. Skip the do/done in for loops.

There’s an undocumented syntax for for loops that works in all versions of bash. The syntax allows you to omit the do and done keywords.

This allows you to write smaller for loops in some cases and is especially useful if you’re code golfing or working with restrictions.

# Undocumented method.
for i in {1..10};{ echo "$i";}

# Expansion.
for i in {1..10}; do echo "$i"; done

# C Style.
for((i=0;i<=10;i++)); do echo "$i"; done

5. Use word splitting to trim whitespace.

Using word splitting we can trim whitespace in strings without any external processes.

Thanks /u/McDutchie

trim() {
    set -f
    set -- $*
    printf "%s\\n" "$*"
    set +f
}

Example:

trim "   hello      world       "

> output: hello world