Search code examples
bashvariablesenvironment-variableszsh

How can I tell if a variable was exported or not in zsh (or bash)?


On the terminal how can I easily distinguish between

  1. a shell variable: foo=foovalue

and

  1. an exported environment variable: export bar=barvalue, usable by child processes ?

I know of set and env commands. set reports both cases, without indicating which is which. env does not report 1).

Sample terminal session

(on zsh + macos but that shouldn't matter overmuch):

$foo=foovalue           
$export bar=barvalue    

$set | egrep "^foo|^bar"
bar=barvalue
foo=foovalue

$env | egrep "^foo|^bar"
bar=barvalue

Any way to see both foo and bar, but also indicate that foo is a bash-only variable that will NOT be visible to child processes like a Python or Ruby script? Typically, when my scripts don't see what I expect, what I end up doing is grepping my shell scripts and looking for where the variable was defined. It works, but it's clunky at best.


Solution

  • Use declare -p and inspect the output. For example:

    declare -- BASH="/bin/bash"
    declare -x EDITOR="vim"
    

    It's obvious which one is exported or not.