Shell变量在命令行上可用,但在脚本中不可用 [英] Shell variable is available on command line but not in script

查看:221
本文介绍了Shell变量在命令行上可用,但在脚本中不可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在bash命令行中,我设置了一个变量myPath=/home/user/dir.我创建了一个脚本,在其中放置了echo $myPath,但它似乎不起作用.它没有回声.如果我在命令行中写echo $myPath,它将起作用,但在脚本中不起作用.

In the bash command line, I set a variable myPath=/home/user/dir . I created a script in which I put echo $myPath but it doesnt seem to work. It echoes nothing. If I write echo $myPath in the command line, it works, but not in the script.

如何访问脚本中的myPath变量?

What can I do to access the myPath variable in the script?

推荐答案

导出变量:

export myPath=/home/user/dir

这指示外壳程序使变量在外部进程和脚本中可用.如果您不export变量,则将其视为当前shell的局部变量.

This instructs the shell to make the variable available in external processes and scripts. If you don't export the variable, it will be considered local to the current shell.

要查看当前导出的变量的列表,请使用env.这也可以用来验证变量是否已正确定义和导出:

To see a list of currently exported variables, use env. This can also be used to verify that a variable is correctly defined and exported:

$ env | grep myPath
myPath=/home/user/dir

这篇关于Shell变量在命令行上可用,但在脚本中不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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