hock
hock

Reputation: 169

How to hide part of unused variable at script startup

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

Answers (4)

xhienne
xhienne

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

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

Use Built-In Conditional Expressions; Verify with Parameter Expansion

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

L&#233;a Gris
L&#233;a Gris

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

tink
tink

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

Related Questions