为什么"var = value echo $ var"不发出值? [英] Why doesn't ''var=value echo $var'' emit value?

查看:41
本文介绍了为什么"var = value echo $ var"不发出值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想验证我对这些情况为何表现不同的理解:

Wanted to validate my understanding of why these situations behave differently:

我认为发生#1是因为赋值和echo在shell中作为单个命令运行,并且在执行echo时未设置$ SOME_VAR(shell在执行之前扩展了所有变量).

I think #1 happens because the assignment and echo run as a single command in the shell and $SOME_VAR is not set when echo executes (shell expands all variables before execution).

#1
$ unset SOME_VAR
$ SOME_VAR=abcdef  echo $SOME_VAR # prints nothing

我认为发生#2是因为赋值和echo在同一shell中作为两个单独的命令运行,并且在执行echo时在shell中设置了$ SOME_VAR.

I think #2 happens because the assignment and echo run as two separate commands in the same shell and $SOME_VAR is set in the shell when echo executes.

#2
$ unset SOME_VAR
$ SOME_VAR=abcdef   ; echo $SOME_VAR
abcdef

我不明白为什么会发生#3 .

#3
$ unset SOME_VAR
$ SOME_VAR=abcdef   ./test.sh # prints abcdef 
abcdef

我认为发生#4的原因是,shell脚本的赋值和执行是在父shell中作为两个不同的命令执行的,而在test.sh中执行命令的子shell不会继承SOME_VAR(因为没有export语句).

I think #4 happens because assignment and execution of shell script execute as two different commands in the parent shell and the child shell that executes commands in test.sh does not inherit SOME_VAR (since there is no export statement).

#4
$ unset SOME_VAR
$ SOME_VAR=abcdef   ; ./test.sh # prints nothing

test.sh包含:

test.sh contains:

$ cat test.sh
#!/bin/bash

echo $SOME_VAR

推荐答案

示例1发生是因为变量扩展首先发生.在这种情况下,事件的顺序为:

Example 1 happens because variable expansion happens first. The order of events in this case is:

  1. 展开 $ SOME_VAR (为空字符串)
  2. SOME_VAR 设置为 abcdef
  3. 调用 echo (没有参数,因为 $ SOME_VAR 扩展为空字符串)
  1. Expand $SOME_VAR (to an empty string)
  2. Set SOME_VAR to abcdef
  3. Call echo (with no args because $SOME_VAR expanded to an empty string)

正如您所说,示例2的发生是因为命令是分别运行的.

Example 2 happens, as you say, because the commands are run separately.

之所以发生示例3,是因为在调用 ./test.sh 之前,将 SOME_VAR 设置为 abcdef ,并且它是<将运行code> ./test.sh .这实际上是习惯用法 VAR = value命令的目的.您希望 command 能够使用 VAR,但您不一定希望所有其他命令或子 shell 都能看到它.

Example 3 happens because SOME_VAR is set to abcdef prior to calling ./test.sh, and is part of the environment that ./test.sh is run in. This is actually the purpose of the idiom VAR=value command. You want command to be able to use VAR, but you don't necessarily want every other command or subshell to see it.

之所以发生示例4,是因为 SOME_VAR 是当前外壳程序中的局部变量,并且尚未进行 export -ed操作,因此子外壳程序可以使用它.

Example 4 happens because SOME_VAR is a local variable in the current shell and has not been export-ed so that subshells can use it.

示例5将是:

unset SOME_VAR
export SOME_VAR=abcdef ; ./test.sh # prints abcdef

这篇关于为什么"var = value echo $ var"不发出值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆