Interview Prep/Shell Scripting/Variables, quoting and expansions

What does `declare` do? Name the useful flags.

IntermediateConceptVariables, quoting and expansions
Answer

declare (same as typeset) sets attributes on variables:

  • -r read-only, -x export, -i integer (assignments are evaluated arithmetically)
  • -a indexed array, -A associative array
  • -l / -u force lower/upper case on assignment
  • -n nameref (reference to another variable)
  • -g make global from inside a function
  • -p NAME print the definition, -f NAME print a function
declare -r CONFIG=/etc/opskit/opskit.conf
declare -A ports=([http]=80 [https]=443)
declare -p ports

Inside a function, declare behaves like local unless you add -g.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Variables, quoting and expansions