Reputation: 169
How I can hide variable from using when it is not defined with bash command with this situation:
EXCLUDE_PORTS="--exclude-ports $2"
if [ "${EXCLUDE_PORTS:-}" == "" ]; then
EXCLUDE_PORTS=''
fi
I need to hide also --exclude-ports, when $2 it is not specified. Actually when I don't specified $2 at script startup, script take only first part empty "--exclude-ports", and this is ruining my script.
Upvotes: 3
Views: 194
Reputation: 6134
There is a shorthand for this:
EXCLUDE_PORTS=${2:+--exclude-ports $2}
The shorthand is ${var:+ <alternate value>}
which is empty if var
is unset or empty, and else is substituted by the alternate value.
Now, if you combine this with Léa's answer:
EXCLUDE_PORTS=( ${2:+--exclude-ports "$2"} )
Upvotes: 3
Reputation: 84343
You can refactor this to a single line using the built-in conditional expressions and the Boolean &&
conditional construct. It's also a good idea to use proper quoting. For example:
[[ -n "$2" ]] && EXCLUDE_PORTS="--exclude-ports '$2'"
You can verify the logic here with the :-
parameter expansion like so:
# make sure your environment is clean for testing
unset EXCLUDE_PORTS
# set exactly two positional arguments
set -- one two
# set variable if $2 zero length when expanded
[[ -n "$2" ]] && EXCLUDE_PORTS="--exclude-ports '$2'"
# print variable if set, or message to aid debugging
echo "${EXCLUDE_PORTS:-variable is empty}"
# --exclude-ports 'two'
When you only have one positional parameter:
unset EXCLUDE_PORTS
set -- one
[[ -n "$2" ]] && EXCLUDE_PORTS="--exclude-ports '$2'"
echo "${EXCLUDE_PORTS:-variable is empty}"
variable is empty
Upvotes: 3
Reputation: 19545
Always use/prefer an array when dynamically building arguments:
if [ -n "$2" ]
then EXCLUDE_PORTS=( '--exclude-ports' "$2" )
else EXCLUDE_PORTS=()
fi
echo command "${EXCLUDE_PORTS[@]}" --other-option
Upvotes: 5
Reputation: 15204
Does this work for you?
EXCLUDE_PORTS="--exclude-ports $2"
if [[ $2 == "" ]] || [[ "${EXCLUDE_PORTS:-}" == "" ]]; then
EXCLUDE_PORTS=''
fi
All you need is an OR ||
Upvotes: 1