【问题标题】:Diffrence between bash script.sh and ./script.sh [duplicate]bash script.sh 和 ./script.sh 之间的区别 [重复]
【发布时间】:2021-01-09 12:33:47
【问题描述】:

假设我们有 env.sh 文件,其中包含:

echo $(history | tail -n2 | head -n1) | sed 's/[0-9]* //' #寻找最后输入的命令

使用 bash env.sh 执行此脚本时,输出将为空:

但是当我们使用./env.sh 执行脚本时,我们会得到最后输入的命令:

我只是想知道它们之间的区别

请注意,如果我们在脚本开头添加 #!/bin/bash./env.sh 将不再输出任何内容。

【问题讨论】:

    标签: bash shell


    【解决方案1】:

    默认情况下,BASH 在非交互式 shell 中禁用历史记录。但是,如果您想启用它,可以这样做:

    #!/bin/bash
    
    echo $HISTFILE # will be empty in non-iteractive shell
    
    HISTFILE=~/.bash_history # set it again
    set -o history
    # the command will work now
    history
    

    这样做的原因是为了避免任何 shell 脚本运行的任何命令弄乱历史记录。

    在通过./env.sh 运行时向脚本添加hashbang(意味着文件将被hashbang 中指定的程序解释为脚本)会使用二进制/bin/bash 调用脚本,即通过bash 运行,因此再次不打印任何历史记录。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-28
      • 2016-08-19
      • 2015-04-30
      • 2018-08-26
      相关资源
      最近更新 更多