Linux017 shell环境变量

2020-08-10  本文已影响0人  caoqiansheng

shell通过环境变量(environment variable)来存储有关shell会话和工作环境的信息,它使得用户可以在内存中存储数据,以便程序或者shell中运行的脚本可以轻松的访问到他们
当在linux系统的shell命令行输入一个外部命令时,shell必须搜索系统来找到对应的程序,而PATH环境变量则定义了用于进行命令和程序查找的目录。在Ubuntu系统中,PATH环境变量的内容如下,其中PATH变量通过冒号进行分割


image.png

如果命令或者程序的位置没有被包括在PATH变量中,那么在不使用绝对路径的情况下,shell是无法找到该命令或者运行该程序,它会给我们返回一个报错信息,比如:


image.png
linux系统的应用程序放置可执行文件的目录,通常不在PATH环境变量所包含的目录中,解决办法是保证PATH环境变量包含所有存放应用程序的目录,我们只需要引用原有的PATH值,并将新的PATH路径添加即可

在bash shell中,环境变量有两类

设置用户定义变量

给环境变量赋值

可以通过等号给环境变量赋值,值可以是数字或者字符串,如:


image.png
注意
显示环境变量

通过命令 echo [变量名称],为引用变量
echo命令在linux系统中的意思是命令的输出,很多时候我们引用变量或者运行脚本,但是我们并不知道变量的内容,或者脚本是否运行成功,可以通过echo命令将变量内容或者脚本运行结果返回在终端。

设置环境变量

如前文Linux011 Sra toolkit安装及使用我们在解压软件到相应的文件夹之后,需要设置$PATH

# 将软件的绝对路径增加至PATH变量中可以使用 "$变量名称" 或是 "${变量}"
# 方法1:echo "export PATH=\$PATH:/home/sratoolkit/sratoolkit.2.10.8-ubuntu64/bin" >> ~/.bashrc
# 方法2:echo "export PATH=\${/home/sratoolkit/sratoolkit.2.10.8-ubuntu64/bin}" >> ~/.bashrc
# 方法3
echo "export PATH='$PATH':/home/sratoolkit/sratoolkit.2.10.8-ubuntu64/bin" >> ~/.bashrc
# 刷新bashrc文件
source ~/.bashrc
# 查看是否可以调用程序
fastq-dump -h
删除环境变量

unset命令

unset: unset [-f] [-v] [-n] [name ...]
    Unset values and attributes of shell variables and functions.

    For each NAME, remove the corresponding variable or function.

    Options:
      -f        treat each NAME as a shell function
      -v        treat each NAME as a shell variable
      -n        treat each NAME as a name reference and unset the variable itself
                rather than the variable it references

    Without options, unset first tries to unset a variable, and if that fails,
    tries to unset a function.

    Some variables cannot be unset; also see `readonly'.

    Exit Status:
    Returns success unless an invalid option is given or a NAME is read-only.

需要注意的是unset命令删除变量,不能使用$引用变量,如:


image.png
命令的别名

alias命令

alias: alias [-p] [name[=value] ... ]
    Define or display aliases.

    Without arguments, `alias' prints the list of aliases in the reusable
    form `alias NAME=VALUE' on standard output.

    Otherwise, an alias is defined for each NAME whose VALUE is given.
    A trailing space in VALUE causes the next word to be checked for
    alias substitution when the alias is expanded.

    Options:
      -p        print all defined aliases in a reusable format

    Exit Status:
    alias returns true unless a NAME is supplied for which no alias has been
    defined.

如下:


image.png

如果想让重设的命令永久生效,可以将其写入home文件夹下的.bashrc文件,同上

上一篇 下一篇

猜你喜欢

热点阅读