与 `source` 命令相反

yae*_*ael 10 bash source shell-script

source在 bash 脚本中使用该命令来读取/打印变量值

more linuxmachines_mount_point.txt

export linuxmachine01="sdb sdc sdf sdd sde sdg"
export linuxmachine02="sde sdd sdb sdf sdc"
export linuxmachine03="sdb sdd sdc sde sdf"
export linuxmachine06="sdb sde sdf sdd"

source  linuxmachines_mount_point.txt

echo $linuxmachine01
sdb sdc sdf sdd sde sdg
Run Code Online (Sandbox Code Playgroud)

source取消设置变量的反义词是什么?

预期成绩

echo $linuxmachine01

< no output >
Run Code Online (Sandbox Code Playgroud)

Joh*_*024 21

使用子shell(推荐)

在子 shell 中运行 source 命令:

(
source linuxmachines_mount_point.txt
cmd1 $linuxmachine02
other_commands_using_variables
etc
)
echo $linuxmachine01  # Will return nothing
Run Code Online (Sandbox Code Playgroud)

子外壳由括号定义:(...). 当子shell结束时,子shell中设置的任何shell变量都会被遗忘。

使用未设置

这将取消设置导出的任何变量linuxmachines_mount_point.txt

unset $(awk -F'[ =]+' '/^export/{print $2}' linuxmachines_mount_point.txt)
Run Code Online (Sandbox Code Playgroud)
  • -F'[ =]+' 告诉 awk 使用空格和等号的任意组合作为字段分隔符。

  • /^export/{print $2}

    这告诉 awk 选择以 开头的行,export然后打印第二个字段。

  • unset $(...)

    这会在 中运行命令$(...),捕获其标准输出,并取消设置由其输出命名的任何变量。

  • @yael 此外,取消设置变量和撤消其他代码副作用正是 subshel​​l 的用途。他们做到这一点简单而可靠。除非有特殊原因,否则您应该使用子shell。 (8认同)
  • @yael 在不需要时使用额外的进程和循环。意见可能会有所不同,但我认为这并不简单。还有潜在的危险,它假设 `file` 中的每一行都是一个导出语句。 (2认同)