DEV Community

Brandon Rozek
Brandon Rozek

Posted on • Originally published at brandonrozek.com on

Conditional Assignment in Bash

Many programming languages include an quick way to perform a conditional assignment. That is, assigning a variable with a value based on some condition. Normally this is done through a ternary operator. For example, here is how to write it in Javascript

age = 16;
ageType = (age > 18) "Adult": "Child";

Enter fullscreen mode Exit fullscreen mode

The variable ageType is dependent upon the value of age. If it is above 18 then ageType = "Adult" otherwise ageType = "Child".

A more verbose way of accomplishing the same thing is the following:

if (age > 18) {
    ageType = "Adult"
} else {
    ageType = "Child"
}

Enter fullscreen mode Exit fullscreen mode

How do we do conditional assignment in Bash? One way is to make use of subshells and echoing out the values.

AGE_TYPE=$([$AGE -gt 18] && echo "Adult" || echo "Child")

Enter fullscreen mode Exit fullscreen mode

A common programming feature called short-circuiting makes it so that if the first condition ([$AGE -gt 18]) is false, then it will skip the right side of the AND (&&) expression. This is becauseFalse && True is always False. However, False || True is equal to True, so the language needs to evaluate the right part of an OR (||) expression.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay