在 Linux shell 中设置变量时 set、env、declare 和 export 有什么区别?

在 Linux shell 中设置变量时 set、env、declare 和 export 有什么区别?

在 Linux shell 中设置变量时setenvdeclare和之间有什么区别,例如?exportbash

答案1

首先你必须明白,environment variablesshell variables不是一回事。

那么,你应该知道贝壳有属性它控制着它的工作方式。这些属性不是环境变量也不是 shell 变量。

现在,开始回答你的问题。

  1. env:不带任何选项,显示当前环境变量-i及其值;但是可以使用标志为单个命令设置环境变量
  2. set:不带选项,每个选项的名称和值shell 变量显示* ~man set在 rhel 中运行;也可用于设置shell 属性. 此命令才不是环境或 shell 变量
  3. declare: 不带任何选项,与 ; 一样,env也可用于设置shell 变量
  4. export:使shell 变量 环境变量

简而言之:

  1. set未设置 shell 或环境变量
  2. env可以为单个命令设置环境变量
  3. declare设置 shell 变量
  4. export使 shell 变量成为环境变量

笔记 declare -x VAR=VAL创建 shell 变量并将其导出,使其成为环境变量。

答案2

看起来 set 和 declared 稍有不同,set 的功能更强大。

请参阅“声明”https://www.gnu.org/software/bash/manual/bash.html#Bash-Builtins 声明:“声明变量并赋予其属性。如果没有给出名称,则显示变量的值。

设置“设置”下https://www.gnu.org/software/bash/manual/bash.html#The-Set-Builtin * set:“这个内置命令非常复杂,值得用自己的部分来描述。set 允许您更改 shell 选项的值并设置位置参数,或者显示 shell 变量的名称和值。”

ENV 是 Bash 中的环境变量: https://www.gnu.org/software/bash/manual/bash.html#Bash-Variables env 是一个 Linux 命令。我认为这是一个很好的参考: https://unix.stackexchange.com/questions/103467/what-is-env-command-doing

我认为这是对出口的一个很好的解释: http://www.unix.com/302531838-post2.html

还: https://www.gnu.org/software/bash/manual/bash.html#Bourne-Shell-Builtins * export(来自 Bourne):“标记每个要传递给环境中的子进程的名称。”

从上面的 URL 借用代码:

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 ~#

相关内容