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:
|&
is shorthand for2>&1
, as it sends cmd1’s stderr, in addition to its stdout to cmd2’s stdin via the pipe.;&
is analogous to acontinue
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.( *commands* )
executes commands in a subshell.{ *commands*; }
executes commands in the current shell. The semicolon (or newline) is required.Bash has builtin support for concurrency through its
coproc
command (see coprocesses section in the bashref manual)An alternative substitute for
xargs
is GNU ParallelTo assign a pointer to a variable, one can use the nameref attribute using the
-n
option todeclare
orlocal
. It creates a reference to another variable, thus allowing you to manipulate the variable indirectly.Bash supports the following tilde expansions:
~+
=> expands to the $PWD~-
=> expands to $OLDPWDWhen doing command substitution,
$(cat cmd)
can be replaced by$(< cmd)
. Although they are both equivalent, the latter is faster.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.