What is the difference between set, env, declare and export when setting a variable in a Linux shell?

What is the difference between set, env, declare and export when setting a variable in a Linux shell, such as bash?

1

2 Answers

First, you must understand that environment variables and shell variables are not the same thing.

Then, you should know that shells have attributes which govern how it works. These attributes are not environment nor shell variables.

Now, on to answering your question.

  1. env: without any options, shows current environment variables with their values; However can be used to set environment variable for a single command with the -i flag
  2. set: without options, the name and value of each shell variable are displayed* ~ from running man set in rhel; can also be used to set shell attribute. This command DOES NOT set environment nor shell variable.
  3. declare: without any options, the same as env; can also be used to set shell variable
  4. export: makes shell variables environment variables

In short:

  1. set doesn't set shell nor environment variables
  2. env can set environment variables for a single command
  3. declare sets shell variables
  4. export makes shell variables environment variables

NOTEdeclare -x VAR=VAL creates the shell variable and also exports it, making it environment variable.

7

It seems that set and declare are slightly different, with set being more powerful.

See "declare" under declare: "Declare variables and give them attributes. If no names are given, then display the values of variables instead.

Set "set" under * set: "This builtin is so complicated that it deserves its own section. set allows you to change the values of shell options and set the positional parameters, or to display the names and values of shell variables."

ENV is an environment variable in Bash: env is a Linux command. I think this is a good reference:

I thought this was a good explanation of export:

Also: * export (from Bourne): "Mark each name to be passed to child processes in the environment."

Borrowing code from URL above:

root@linux ~# x=5 <= here variable is set without export command
root@linux ~# echo $x
5
root@linux ~# bash <= subshell creation
root@linux ~# echo $x <= subshell doesnt know $x variable value
root@linux ~# exit <= exit from subshell
exit
root@linux ~# echo $x <= parent shell still knows $x variable
5
root@linux ~# export x=5 <= specify $x variable value using export command
root@linux ~# echo $x <= parent shell doesn't see any difference from the first declaration
5
root@linux ~# bash <= create subshell again
root@linux ~# echo $x <= now the subshell knows $x variable value
5
root@linux ~#
3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like