1

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.

1
  • 1
    If you don't mind a trailing / then simple MY_PATH="$WORKING_DIR/$MY_FILE_NAME" will also work Commented Oct 14, 2013 at 18:04

2 Answers 2

2

Following should work for you:

[[ $MY_FILE_NAME ]] && MY_PATH="$WORKING_DIR/$MY_FILE_NAME" || MY_PATH="$WORKING_DIR"
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! This worked. I realized I posted a stupid question when I first saw your comment. It's fine if extra trailing slashes get added.
Ah in that case you just needed MY_PATH="$WORKING_DIR/$MY_FILE_NAME"
2

try this :

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

2 Comments

This will add an extra / in the end and OP wrote If the variable MY_FILE_NAME is not set then MY_PATH should be same as value of WORKING_DIR.
Thanks, I think it be simplified to: MY_PATH=${WORKING_DIR}${MY_FILE_NAME:+/}${MY_FILE_NAME}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.