我总是使用运行脚本 ./
例如 ./script.sh
我最近了解到你也可以输入 . script.sh
有什么区别吗?
第二个对我来说要容易得多,因为我的键盘没有 / 键,但我需要按SHIFT -
。
当你这样做时./script.sh
,脚本在子shell中运行。因此,脚本要执行的任何操作/更改都在子shell 中进行,因此父shell,即来自调用脚本的shell 的父shell 不会受到更改的影响。
另一方面,当你这样做时. script.sh
(.
与 shell builtin 相同source
),脚本是 source 意味着所有命令都在这个 shell 实例中执行(从它被调用)。因此,变量、函数声明等属性的任何更改都会影响 shell。
通常source
用于用户配置文件,例如~/.bashrc
在对其进行任何修改后,例如添加新路径到PATH
,以便从当前 shell 会话应用更改。
也许一个例子会让你更清楚:
$ cat script.sh ##Our test script, containing just a variable (spam) declaration
#!/bin/bash
spam=foobar
$ ./script.sh ## Execute using ./script.sh
$ echo "$spam" ## Prints nothing
$ . script.sh ## Lets source it
$ echo "$spam" ## Now we get it
foobar
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2119 次 |
最近记录: |