Thursday, February 1, 2018 [Tweets] [Favorites]

Things I Wish I’d Known About Bash

zwischenzugs (via Hacker News):

The difference between [ and [[ was another thing I never really understood. [ is the original form for tests, and then [[ was introduced, which is more flexible and intuitive. In the first if block above, the if statement barfs because the $(grep not_there /dev/null) is evaluated to nothing, resulting in this comparison:

[ = '' ]

which makes no sense. The double bracket form handles this for you.

This is why you occasionally see comparisons like this in bash scripts:

if [ x$(grep not_there /dev/null) = 'x' ]

so that if the command returns nothing it still runs. There’s no need for it, but that’s why it exists.

[…]

Bash has configurable options which can be set on the fly. I use two of these all the time:

set -e

exits from a script if any command returned a non-zero exit code (see above).

This outputs the commands that get run as they run:

set -x

zwischenzugs (Hacker News):

  • The # means ‘match and remove the following pattern from the start of the string’
  • The % means ‘match and remove the following pattern from the end of the string

[…]

The trap builtin can be used to ‘catch’ when a signal is sent to your script.

Previously: Mac Terminal Tips, Craig’s Terminal Tips.

Update (2018-02-05): Der Teilweise:

It’s wrong regading !$:

!$ is not the last argument of the previous command. It’s the last word. The last argument is $_.

Given echo x>/dev/null:

$_ is x

!$ is /dev/null

1 Comment

[…] Things I Wish I’d Known About Bash, Mac Terminal Tips, Craig’s Terminal […]

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment