One liner if-else not working as intended

134 Views Asked by At

I made a simple script on WSL for windows 11 to mount my pen drive. The default option is to mount it from D:, and I can specify as an argument if the pen drive is in another place.

The script is like this:

#! /bin/bash

[[ $# -eq 0 ]] && sudo mount -t drvfs D: /pen || sudo mount -t drvfs ${1}: /pen

[[ $? == 0 ]] && echo "Good" || echo "Bad"

It works when the pen drive is connected on port D:, but when there is no pen drive connected, the first command executes both sides of the OR.

I am expecting it to execute on the same basis of al if-else statement. If the condition is true, it executes the left side, and if it is false, it executes the right side.

1

There are 1 best solutions below

0
Taras Khalymon On

This construction (so called one-line if statement) uses executable part as a condition assuming that it's true. But if "true" part returns false, second part will also be executed.

Here's the example:

[[ 0 == 0 ]] && (echo "Good"; exit 1) || echo "Bad"

Condition is true, but executable part after it returns false (exit 1), so [[ 0 == 0 ]] && (echo "Good"; exit 1) part is false and we should check another condition of || operator.

As a result, we are executing both true and false parts.

If you need to fit it into a single line, you can add || true to "true" part:

[[ 0 == 0 ]] && (echo "Good" || true) || echo "Bad"

In this case, even if echo "Good" returns false, the whole "true" part will return true and false second part of || will not be checked.