Bash create a path with variables divided by _ and check if exist

Viewed 46

In Bash, I am trying to create a path with two variables within:

/path/to/my/file/${variable1_-}${variable2}/Still/some/path

My variable2 is always set, but the variable1 might be empty and in that case I don't want to print the "_"

I have tried the line above, but doesn't seem to be correct. Can someone help in getting the right path printed?

Thanks in advance for your suggestions!

3 Answers

You have a simple typo (the underscore should be after the separator, not part of the variable name) and you want to include the underscore if variable1 is set, not it it's unset (so plus instead of minus in the parameter expansion; and add a colon to also cover the set but empty case). Presumably you also want to include the actual value of variable1 when it's set.

/path/to/my/file/${variable1}${variable1:+_}${variable2}/Still/some/path

or equivalently, nested

/path/to/my/file/${variable1:+${variable1}_}${variable2}/Still/some/path

where the braces before the underscore are necessary to separate the variable name from the literal text.

You can use this. https://linux.die.net/man/1/bash ${parameter:+word}

set also variable1

variable1=VAR1
variable2=VAR2
variable3=${variable1:+_}
echo /path/to/my/file/${variable1}${variable3}${variable2}/Still/some/path

set only variable2

variable1=
variable2=VAR2
variable3=${variable1:+_}
echo /path/to/my/file/${variable1}${variable3}${variable2}/Still/some/path

With a few more lines of code this could work:

run () {
    prefix="" # empty
    if [ -n "$variable1" ]; then
        prefix="${variable1}_"
    fi
    echo "/path/to/my/file/${prefix}${variable2}/Still/some/path"
}

# set only variable2
variable2=var2
run
# set also variable1
variable1=var1
run

output:

/path/to/my/file/var2/Still/some/path
/path/to/my/file/var1_var2/Still/some/path

description:

-n tests if the string is not empty, in that case I fill prefix with variable1 and the underscore

Related