Declare command

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
  • Use the declare command to set variable and functions attributes.

Create a constant variable

  • A constant variable is a variable that is always constant in the experiment, it never changes.
  • Also known as readonly variable and syntax is:
declare -r var
declare -r varName=value

For example, create a constant variable called pwdfile, enter:

declare -r pwdfile=/etc/passwd

To display the value of a variable ($pwdfile) either use [[|Echo command|echo or printf command]] as follows:

echo $pwdfile

However, the following will result into an error:

pwdfile=/etc/foo.txt

Sample outputs:

bash: pwdfile: readonly variable

Create an integer variable

  • An integer data type (variable) is any type of number without a fractional part.
  • The syntax is as follow to make variable have the integer attribute:
declare -i var
declare -i varName=value
  • For example, define y as an integer number:
declare -i y=10
[ $y -eq 0 ] && echo "Y is set to a zero number." || echo "Y is set to a nonzero number."

Now, try to set y to something else:

y="foo"
[ $y -eq 0 ] && echo "Y is set to a zero number." || echo "Y is set to a nonzero number."

Without an integer attribute the test command will return an error:

z=10
[ $z -eq 0 ] && echo "Z is set to a zero number." || echo "Z is set to a nonzero number."
z="foo"
[ $z -eq 0 ] && echo "Z is set to a zero number." || echo "Z is set to a nonzero number."

Sample outputs:

bash: [: foo: integer expression expected
Z is set to a nonzero number.

See also