0

From Bash manual, a parameter is set if it has been assigned a value.

  1. In bash, are the following two different concepts:

    • a variable exists
    • a variable has been assigned a value, i.e. is set?
  2. unset removes a variable or function. Does unset make a variable

    • become non-existent, or
    • still exists but become not assigned any value?
  3. Does b= assign a value to variable b? Is b set now?

  4. Does declare a variable creates a variable i.e. make a variable become exist?

1 Answer 1

3

Variable does not exist if it's not set. For example,

unset var
echo ${var?"this is not set"}
-bash: var: this is not set

The shell displays an error message if var is not set. The echo is not executed. (Check the bash man page for ways to check and assign values to a variable that exists, but may or may not have a value, or one that doesn't exist.)

The more usual case is often substitution without an error, and would be handled like this:

unset var
echo ${var:-This is a new value}
This is a new value

Variable exists and has a value. For example,

var=123
echo ${var?"this is not set"}
123

Variable exists but is empty ("")

var=
echo ${var?"this is not set"}

The echo outputs the value of var, which is nothing, followed by its usual newline

Assigning a value is just like this:

var=123
echo $var
123

declare is used to assign attributes to a variable (check the bash man page for typeset or declare under the **shell builtin commands** for details.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.