Shell[三]: source命令

来源:互联网 发布:淘宝扣除保证金的规则 编辑:程序博客网 时间:2024/06/05 14:36

Shell[三]: source命令


souce 用法:

1. 正常使用: $source FileName2. 相同意思其他用法: . FileName # 点与文件名之间有空格作用:     在当前bash环境下读取并执行FileName文件中的内容.

source 命令与 sh other_script的区别是:

source在当前bash环境下执行命令, 而/bin/sh other_script.sh是启动一个子shell来执行命令。假如在 test.sh 文件中 引入 test2.sh 并执行,test.sh的主环境就会 暂停 去加载执行test2.sh文件中的内容,在test2.sh文件中的环境变量会 在test2.sh执行完成后,在test.sh依然可以使用。示例:
##-------- test2.sh#! /bin/shB="BBBB"echo " I am in test2.sh B = "$B##-------- test.shA="hello world"echo " I am in test.sh , content="$Aecho " start to run test2.sh"source test2.shecho " test2.sh running over"echo " print variablb B"echo " I am in test.sh B = "$B##-------- 结果# ./test.sh  I am in test.sh , content=hello world start to run test2.sh I am in test2.sh B = BBBB test2.sh running over print variablb B I am in test.sh B = BBBB
如果source了一个sh文件,其中定义了一个变量B,这时在当前shell环境中,就有了 环境变量B,如果想删除这个环境变量就用 unset命令。
# source ./test.sh  I am in test.sh , content=hello world start to run test2.sh I am in test2.sh B = BBBB test2.sh running over print variablb B I am in test.sh B = BBBB# echo $BBBBB# unset B# echo $B    ## (空的,没有任何值)# 
原创粉丝点击