lvrz.org

[TIL]: Bash Tidbits (part I)

Every now and then I peruse usr/share/doc and read the resident documentation in my OS. Today, I went through the Bash manual while sitting idle without an internet connection. I picked up a few nuggets along the way:

  1. |& is shorthand for 2>&1, as it sends cmd1's stderr, in addition to its stdout to cmd2's stdin via the pipe.

  2. ;& is analogous to a continue keyword in most languages. In case of switch statements, it forces the execution to fallthrough. ;;& makes the shell test the patterns in the next clause, and it executes it if the match is successful.

  3. ( *commands* ) executes commands in a subshell.

  4. { *commands*; } executes commands in the current shell. The semicolon (or newline) is required.

  5. Bash has builtin support for concurrency through its coproc command (see coprocesses section in the bashref manual)

  6. An alternative substitute for xargs is GNU Parallel

  7. To assign a pointer to a variable, one can use the nameref attribute using the -n option to declare or local. It creates a reference to another variable, thus allowing you to manipulate the variable indirectly.

  8. Bash supports the following tilde expansions: ~+ => expands to the $PWD ~- => expands to $OLDPWD

  9. When doing command substitution, $(cat cmd) can be replaced by $(< cmd). Although they are both equivalent, the latter is faster.

  10. An interesting feature of parallel is that it can preserve the order of its inputs with the -k flag. For example:

    { echo example.com; echo catb.org; echo gnu.org; } | parallel -k traceroute
    

    This will display the output in order of its inputs, vice the alternative; which displays whichever traceroute invocation that finishes first.

Happy hacking!

#bash #til