[英]Bash: Creating a shell variable in a bash script that I can access from command line
I have very little experience working with bash.我使用 bash 的经验很少。 With that being said I need to create a bash script that takes your current directory path and saves it to a shell variable.
话虽如此,我需要创建一个 bash 脚本,该脚本采用您当前的目录路径并将其保存到 shell 变量中。 I then need to be able to type "echo $shellvariable" and have that output the directory that I saved to that variable in the bash script.
然后,我需要能够键入“echo $shellvariable”并让 output 成为我在 bash 脚本中保存到该变量的目录。 This is what I have so far.
这就是我到目前为止所拥有的。
#!/bin/bash
mypath=$(pwd)
cd $1
echo $mypath
exec bash
now when I go to command line and type "echo $mypath" it outputs nothing.现在,当我将 go 输入命令行并输入“echo $mypath”时,它什么也不输出。
You can just run source <file_with_your_vars>
, this will load your variables in yours script or command line session.您可以只运行
source <file_with_your_vars>
,这将在您的脚本或命令行 session 中加载您的变量。
> cat source_vars.sh
my_var="value_of_my_var"
> echo $my_var
> source source_vars.sh
> echo $my_var
value_of_my_var
You have to export
the variable for it to exist in the newly- exec
ed shell:您必须
export
变量以使其存在于新执行的exec
中:
#!/bin/bash
export mypath=$(pwd)
cd $1
echo $mypath
exec bash
'env -i' gives control what vars a shell/programm get... 'env -i' 可以控制 shell/程序获得的变量...
#!/bin/bash
mypath=$(pwd)
cd $1
echo $mypath
env -i mypath=${mypath} exec bash
...ie with minimal environment. ...即最小的环境。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.