当我使用bash脚本时,$ 0不起作用

Mor*_*rad 10 bash csh

我有一个简单的脚本test.sh

#!/bin/bash
echo $0
Run Code Online (Sandbox Code Playgroud)

当我从csh终端运行以下命令时:

bash -c 'test.sh'
Run Code Online (Sandbox Code Playgroud)

然后输出是 test.sh

但是当我跑步时:

bash -c 'source test.sh'
Run Code Online (Sandbox Code Playgroud)

输出是 bash

在这种情况下,有人知道如何打印脚本名称吗?

bob*_*bah 8

#!/bin/bash
declare -r SCRIPT_NAME=$(readlink -f ${BASH_SOURCE[0]})
Run Code Online (Sandbox Code Playgroud)


Aro*_*fis 7

使用$ BASH_SOURCE。从手册页:

BASH_SOURCE
       An  array  variable whose members are the source filenames where
       the corresponding shell function names  in  the  FUNCNAME  array  
       variable  are  defined.   The  shell function ${FUNCNAME[$i]} is
       defined  in  the  file  ${BASH_SOURCE[$i]}   and   called   from   
       ${BASH_SOURCE[$i+1]}.
Run Code Online (Sandbox Code Playgroud)

您可以简单地引用$ BASH_SOURCE而不是$ {BASH_SOURCE [0]},因为在bash中取消引用没有索引的数组变量将为您提供第一个元素。

这是我脚本中的一种常见模式,它允许在执行脚本和执行脚本时采用不同的行为:

foo() {
    some cool function
}

if [[ "$BASH_SOURCE" == "$0" ]]; then
    # actually run it
    foo "$@"
fi
Run Code Online (Sandbox Code Playgroud)