Search code examples
bashshellbrace-expansion

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.


Solution

  • Following should work for you:

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