shell 的source指令和.指令

目录

译文

示例1

示例2

原文

. (source or dot operator)


译文

译自source or dot operator Man Page - Linux - SS64.com

source/.的作用都是读取文件内容,然后依照内容执行指令。

语法:

source 文件名 参数
. 文件名 参数

在bash中source是.的同义词。但是POSIX不认source。所以为了兼容性,建议任何场合都使用.

使用source运行某文件,文件的指令都在当前shell下执行,且该文件中创建的变量,或者对变量做的改变,在文件运行结束后,仍然对当前shell有效。假如不使用source或者.,只运行文件名,那么文件内的命令将在一个子shell里运行(子shell的变量也是独立的)。

示例1

 

.与文件名之间留空格和不留空格的效果是有细微区别的。.文件名     . 文件名

留空格的话,即使文件不具备运行权限,也可以执行。

示例2

 

#!/bin/bash

echo c

 除非我们在执行脚本文件时,明确了脚本文件的路径,否则shell首先要搜索PATH环境变量。假如PATH的某个路径下有此名称的文件,则shell将执行之;否则将搜索shell的当前路径。

原文

. (source or dot operator)

Read and execute commands from the filename argument in the current shell context.

Syntax
      . filename [arguments]

      source filename [arguments]

source is a synonym for dot/period '.' in bash, but not in POSIX sh, so for maximum compatibility use the period.

When a script is run using source it runs within the existing shell, any variables created or modified by the script will remain available after the script completes. In contrast if the script is run just as filename, then a separate subshell (with a completely separate set of variables) would be spawned to run the script.

There is a subtle difference between executing a script by running .ss64script (dot ss64script) and . ss64script (dot space ss64script)
the first is running a file thats been hidden from the 'ls' command, (although ls -a will show hidden files) the second option will execute ss64script even if it has not been set as an executable with chmod.

Unless you provide an exact path to filename then bash will look first via the PATH variable and then in the current directory (only if filename is not found in $PATH.) 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值