The Governor
The Governor

Reputation: 1192

Construct file path using shell parameter expansion

I need to construct an absolute file path based on the values of two variables in bash. I have the following two variables:

MY_FILE_NAME=myfile-1.0.0.80234.txt ### This variable is NOT guaranteed to be set
WORKING_DIR=/var/my_working_dir     ### This variable is guaranteed to be set
MY_PATH=<Some parameter expansion magic>

If the variable MY_FILE_NAME is set then MY_PATH should have the value:

/var/my_working_dir/myfile-1.0.0.80234.txt

If the variable MY_FILE_NAME is not set then MY_PATH should be same as value of WORKING_DIR. How do I achieve this using parameter expansion preferably in just one line.

Upvotes: 1

Views: 233

Answers (2)

michael501
michael501

Reputation: 1482

try this :

MY_PATH=${WORKING_DIR}${MY_FILE_NAME:+/}${MY_FILE_NAME:-}

Upvotes: 2

anubhava
anubhava

Reputation: 785266

Following should work for you:

[[ $MY_FILE_NAME ]] && MY_PATH="$WORKING_DIR/$MY_FILE_NAME" || MY_PATH="$WORKING_DIR"

Upvotes: 2

Related Questions