gpt4 book ai didi

更改环境变量的 Linux shell 脚本

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:35:30 25 4
gpt4 key购买 nike

我正在尝试编写一个 Linux shell 脚本来将环境变量“ROS_IP”更改为我当前的 IP 地址。

printenv | grep "ROS_IP" 

返回 ROS_IP=192.168.1.10

命令

ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1  -d'/'

返回我当前正确的 ip 地址 192.168.1.2

这是我的shell脚本

#!/bin/bash

#Command to get current IP address and set the output to a variable 'var'
var=$(ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1 -d'/')
#Make sure var is the correct IP
echo $var
#Set ROS_IP
export ROS_IP=$var
#end script

脚本运行后,运行命令

printenv | grep "ROS_IP" 

仍然返回旧的输出 ROS_IP=192.168.1.10

我该如何解决这个问题?

最佳答案

如果您通过以下方式执行脚本,您想要的将无法工作:

bash script.sh  # won't work

或者:

./script.sh  # won't work even if script has executable bit set

相反,您必须获取它:

. script.sh

或者,如果您愿意:

source script.sh

问题是子 shell 不能改变父 shell 的环境。 export 命令适用于运行脚本的 shell 及其子 shell,但其父 shell。因此,命令必须在父 shell 中运行。这就是采购的作用。

文档

采购记录在 man bash 中:

. filename [arguments]
source filename [arguments]
Read and execute commands from filename in the current shell environment and return the exit status of the last command executed from filename. If filename does not contain a slash, filenames in PATH are used to find the directory containing filename. The file searched for in PATH need not be executable. When bash is not in posix mode, the current directory is searched if no file is found in PATH. If the sourcepath option to the shopt builtin command is turned off, the PATH is not searched. If any arguments are supplied, they become the positional parameters when filename is executed. Otherwise the positional parameters are unchanged. The return status is the status of the last command exited within the script (0 if no commands are executed), and false if filename is not found or cannot be read. [emphasis added]

关于更改环境变量的 Linux shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33793075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com