1

Looking for a way to declare a boolean, something like this:

HOME_IS_BASE_DIR=$("home" == "${BASE_DIRECTORY}")    // boolean
USERS_IS_BASE_DIR=$("Users" == "${BASE_DIRECTORY}")   // boolean

except of course the above doesn't work, I get an error:

bash cannot find home command

bash cannot find Users command

the long way to do this would be:

HOME_IS_BASE_DIR=false;
USERS_IS_BASE_DIR=false;

if [ "home" == "${BASE_DIRECTORY}" ]; then
  HOME_IS_BASE_DIR=true;
else if [  "Users" == "${BASE_DIRECTORY}" ]; then
  USERS_IS_BASE_DIR=true;
fi

is there a shorthand for this?

4

A more compact representation can be achieved with something like the following

#!/bin/sh         
BASE_DIRECTORY="home";
[ "home" == "$BASE_DIRECTORY" ] && HOME_IS_BASE_DIR=true || HOME_IS_BASE_DIR=false;
echo $HOME_IS_BASE_DIR;
  • @alexander-mills your edit is correct. I just provided a more general example :) – jsalatas Dec 9 '16 at 0:42
  • thanks, I like specific examples, it's more clear to the reader :) – Alexander Mills Dec 9 '16 at 0:44
  • Your second edit was confusing IMHO. It wouldn't even run at all if you didn't define $FOO :) – jsalatas Dec 9 '16 at 0:47
1
case ${BASE_DIRECTORY} in
    "home")
        HOME_IS_BASE_DIR=true
        USERS_IS_BASE_DIR=false
        ;;
    "Users")
        HOME_IS_BASE_DIR=false
        USERS_IS_BASE_DIR=true
        ;;
    *)
        # Handle heretofore unhandled values here
        ;;
esac

It's not exactly shorthand, but it's a both very clear what you're doing, and easy to extend to other locations. Rather than using those extra variables, though, why not just look at ${BASE_DIRECTORY} directly?

  • thanks, the reason I don't want to look at $BASE_DIRECTORY directly is because I wanted to use shorthand later in some other functionality – Alexander Mills Dec 9 '16 at 19:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.