Reputation: 115
I am trying to make Gitlab CI/CD for building unity3d
project automatically
and I did end up with long argument to execute build procedure. Now i'd like to make the script more dynamic for case where some args doesn't really needed e.g case differentiating android build that require key store or not.
So far what I ended up with this
/path/to/unity/unity -other args \
$([ ! -z $UNITY_ASSETS_EXPORT] && -assetPathNames $UNITY_ASSETS_EXPORT)
but it doesn't output anything thus require me to use echo command. Is there any better way for me so I don't litter most of my script with echo
for each variable cases ?
Upvotes: 2
Views: 702
Reputation: 181785
echo
is definitely one way, and remains the most flexible, and arguably the most readable:
/path/to/unity/unity -other args \
$([ ! -z $UNITY_ASSETS_EXPORT ] && echo "-assetPathNames $UNITY_ASSETS_EXPORT")
However, in this simple case, you can use bash's variable expansion with the ${parameter:+word}
construct. It expands to word
if parameter
is nonempty, otherwise it expands to nothing:
/path/to/unity/unity -other args \
${UNITY_ASSETS_EXPORT:+-assetPathNames $UNITY_ASSETS_EXPORT}
Upvotes: 1
Reputation: 85663
Your idea was right, but the way you have handled the optional argument is incorrect. The expression you have
$([ ! -z $UNITY_ASSETS_EXPORT ] && -assetPathNames $UNITY_ASSETS_EXPORT)
evaluates to below when the variable is set
$(-assetPathNames $UNITY_ASSETS_EXPORT)
since the $(..)
is a command substitution syntax meant to execute the contents as commands, the result is treated as a command to run which is incorrect.
Use a placeholder like an array to store the args and pass it to the command.
unity_arg=([ ! -z "$UNITY_ASSETS_EXPORT" ] && -assetPathNames "$UNITY_ASSETS_EXPORT")
and now pass the array contents to your command
/path/to/unity/unity -other args "${unity_arg[@]}"
The array expansion will produce the right argument strings when the variable is defined and expand to nothing when the variable is empty.
Upvotes: 1