2

I am going though some growing pains with Unix. My question:

I want to be able to print all my user defined variables in my shell. Let say I do the following in the shell:

$ x=9
$ y="Help"
$ z=-18
$ R="My 4th variable"

How would I go about printing:

x y z R

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
  • Lots of into here: http://stackoverflow.com/questions/15262292/whats-the-difference-of-the-command-output-after-inputting-the-command-env – dcaswell Sep 14 '13 at 16:26
  • you only add the dollar sign when reading the variable value, not when setting it. – mnagel Sep 14 '13 at 16:45
  • Yes. Good call @mnagel. I was trying to "emulate the shell" I suppose. My instructor seems to do that in his notes and it just carried over to what I wrote. – Jason Conrow Sep 14 '13 at 16:59
  • If the `$` is supposed to represent your shell prompt (which is a common convention when showing interactive commands), put a space after it. I'll edit your question accordingly. – Keith Thompson Sep 14 '13 at 21:59

3 Answers3

3

Type set:

$ set
Apple_PubSub_Socket_Render=/tmp/launch-jiNTOC/Render
BASH=/bin/bash
BASH_ARGC=()
BASH_ARGV=()
BASH_LINENO=()
BASH_SOURCE=()
BASH_VERSINFO=([0]="3" [1]="2" [2]="51" [3]="1" [4]="release" [5]="x86_64-apple-darwin13")
BASH_VERSION='3.2.51(1)-release'
COCOS2DROOT=/Users/andy/Source/cocos2d
COLUMNS=80
DIRSTACK=()
...

(Oh, and BTW, you appear to have your variable syntax incorrect as you assign, say, A but print $A)

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
3

You should record your variables first at runtime with set, then compare it later to see which variables were added. Example:

#!/bin/bash

set | grep -E '^[^[:space:]]+=' | cut -f 1 -d = | sort > /tmp/previous.txt

a=1234
b=1234

set | grep -E '^[^[:space:]]+=' | cut -f 1 -d = | sort > /tmp/now.txt

comm -13 /tmp/previous.txt /tmp/now.txt

Output:

a
b
PIPESTATUS

Notice that there are still other variables produced by the shell but is not declared by the user. You can filter them with grep -v. It depends on the shell as well.

Add: Grep and cut could simply be just one sed a well: sed -n 's/^\([^[:space:]]\+\)=.*/\1/p'

konsolebox
  • 72,135
  • 12
  • 99
  • 105
0

If variables are exported then you can use env command in Unix.

anubhava
  • 761,203
  • 64
  • 569
  • 643