Bash Tricks

Some more stuff I have repeatedly looked up, because it’s awesome.

Using command output as a file

Use <(command [args]) to capture the output of command with and pass it on as a file parameter to some other command. Example:

vim <(ls -lh /etc)

Parameter Expansion

Probably everyone reading this knows that in bash the text ${myvariable} will be replaced verbatim with the value of the variable myvariable. This expansion process can be controlled in various useful ways. They are all listed in the “Parameter Expansion” section of bash’s man page. Here’s a shortened excerpt for the ones I use most frequently:

   ${parameter%word}
   ${parameter%%word}
          Remove  matching  suffix  pattern.  The word is expanded to produce a pattern just as in
          pathname expansion.  If the pattern matches a trailing portion of the expanded value  of
          parameter,  then the result of the expansion is the expanded value of parameter with the
          shortest matching pattern (the ``%'' case) or the longest matching pattern  (the  ``%%''
          case) deleted.

   ${parameter#word}
   ${parameter##word}
          As above, but remove prefix.

   ${parameter/pattern/string}
          Pattern substitution.  The pattern is expanded to produce a pattern just as in  pathname
          expansion.   Parameter is expanded and the longest match of pattern against its value is
          replaced with string.  If pattern begins with /, all matches  of  pattern  are  replaced
          with  string.   Normally only the first match is replaced.  If pattern begins with #, it
          must match at the beginning of the expanded value of parameter.  If pattern begins  with
          %,  it  must  match  at  the end of the expanded value of parameter.  If string is null,
          matches of pattern are deleted and the / following  pattern  may  be  omitted.

   ${parameter:?word}
          Display  Error  if  Null or Unset.  If parameter is null or unset, the expansion of word
          (or a message to that effect if word is not present) is written to  the  standard  error
          and  the  shell,  if it is not interactive, exits.  Otherwise, the value of parameter is
          substituted.

   ${parameter:-word}
          Use Default Values.  If parameter is unset or null, the expansion  of  word  is  substi‐
          tuted.  Otherwise, the value of parameter is substituted.

   ${parameter:=word}
          Assign Default Values.  If parameter is unset or null, the expansion of word is assigned
          to parameter.  The value of parameter is then substituted.   Positional  parameters  and
          special parameters may not be assigned to in this way.

Command Substitution

Using $(command [args]) is similar to the above, but the output of command is used instead of a variable. Backticks can also be used instead of $(): `command`.



Home