Skip to content
shellhacks.dev
Debugging

Print a variable with its type

Print a variable with its attributes using declare -p in Bash. It shows quoting, array form and flags such as read-only, which echo hides.

1 min read
Summarize in AI

A variable holds something unexpected, and echo "$v" hides spaces, array structure and the flags it has.

Shell
name="two words"
list=("a" "b c")
declare -A map=([k1]=v1 [k2]="v 2")
declare -i count=5
readonly pi=3.14
declare -p name list map count pi
Text
declare -- name="two words"
declare -a list=([0]="a" [1]="b c")
declare -A map=([k1]="v1" [k2]="v 2" )
declare -i count="5"
declare -r pi="3.14"

declare -p prints each variable as a declare command that would recreate it, with the attributes: -a for an indexed array, -A for an associative one, -i for an integer and -r for read only. The behavior is listed under declare in the manual. The quoting in the output is the exact value, so a trailing space or an element with spaces is visible.

Run without names, declare -p prints every variable in the shell, which is a lot. The output is meant for Bash to read back, so it is not portable to other shells. For a value that includes control characters, the %q format of printf is the clearer tool.

Share

More snippets

Debugging

Stop on the first error and show where

Report where a script failed with trap '...' ERR and set -E. LINENO gives the line, BASH_COMMAND the command and $? the status, even inside functions.

1 min read
Debugging

Print each line as it is read

Print every script line as the shell reads it, before expansion, with set -v. Pair it with set -x to see the source line and the expanded command.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.