【问题标题】:What's the difference between: ". [script]" or "source [script]", "bash [script] or $SHELL [script]", and "./ [script]" or "[script]"?“. [script]”或“source [script]”、“bash [script] 或 $SHELL [script]”和“./ [script]”或“[script]”之间有什么区别?
【发布时间】:2018-01-27 10:14:59
【问题描述】:

我知道 source. 做同样的事情,如果标题中的其他命令对不是同样的事情,我会感到惊讶(因为我正在运行 bash 作为我的shell,$SHELL [script]bash [script] 是等价的,对吧??)。

那么这三种执行脚本的方法有什么区别呢?我之所以问,是因为我刚刚了解到采购脚本是NOT the exact same 作为执行它。在运行我的“实验”和阅读手册页时我没有发现明显的方式。

通过在我编写的极其简单的脚本上盲目调用这些函数,我找不到其他哪些细微差别?阅读上面链接的答案后,我可以强烈猜测我的问题的答案将是一个非常简单的解释,但我自己几乎永远不会完全发现。

这是我做的“实验”:

$. myScript.sh
  "This is the output to my script. I'd like to think it's original."

$source myScript.sh
  "This is the output to my script. I'd like to think it's original."

$bash myScript.sh
  "This is the output to my script. I'd like to think it's original."

$$SHELL myScript.sh
  "This is the output to my script. I'd like to think it's original."

$./myScript.sh 
  "This is the output to my script. I'd like to think it's original."

$myScript.sh 
  "This is the output to my script. I'd like to think it's original."

【问题讨论】:

    标签: linux bash shell dot-source


    【解决方案1】:

    . scriptsource script在当前环境中执行script的内容,即不创建子shell。从好的方面来说,这允许script 影响当前环境,例如更改环境变量或更改当前工作目录。不利的一面是,这会让script 影响当前环境,这是一个潜在的安全隐患。

    bash scriptscript 传递给bash 解释器以执行。 script 本身给出的任何 shebang 都会被忽略。 (“Shebang”指的是script的第一行,例如可以读作#!/bin/bash,或#!/usr/bin/perl,或#!/usr/bin/awk,以指定要使用的解释器。)

    $SHELL scriptscript 传递给你当前的shell 解释器 来执行。这可能是,也可能不是bash。 (环境变量SHELL保存了你当前shell解释器的名称。$SHELL,如果运行bash,则计算为/bin/bash,效果在上一段中详述。)

    ./script 在当前工作目录中执行文件script 的内容。如果没有这样的文件,则会产生错误。 $PATH 的内容对发生的事情没有影响。

    script$PATH 中列出的目录中查找文件script,该目录可能包括也可能不包括当前工作目录。在此目录列表中找到的第一个 script 被执行,它可能是也可能不是您当前工作目录中的那个。

    【讨论】:

    • 啊,谢谢!所以我可以运行不同的 shell(比如 csh),但仍然调用bash [script]。关于shebang的附加部分很有趣!所以“$SHELL [script]”也会忽略shebangs。我刚刚意识到的另一件事是,我在运行实验时所在的目录位于我的 $PATH 变量中。如果不是这样,“[脚本]”根本就行不通。哇。这种看似相似的输出有很多差异。
    • @AriSweedler:没错。请注意,某些工具会忽略您当前的shell,并默认为/bin/sh,除非明确另有说明(例如crontab和make)。
    • 备注:source 是 Bashism,. 是 POSIX; $SHELL 可能会扩展到您的 shell 以外的其他内容(例如,在运行 dash 时是 /bin/bash)。
    猜你喜欢
    • 2011-05-13
    • 2018-12-08
    • 1970-01-01
    • 2014-11-02
    • 2023-04-03
    • 2011-08-23
    • 2016-08-06
    • 1970-01-01
    • 2012-08-24
    相关资源
    最近更新 更多