如何知道Bash脚本中的脚本文件名?

时间:2022-10-16 13:58:02

How can I determine the name of the Bash script file inside the script itself?

如何确定脚本内部Bash脚本文件的名称?

Like if my script is in file runme.sh, then how would I make it to display "You are running runme.sh" message without hardcoding that?

就像我的脚本在文件runme中一样。嘘,那我该如何显示“你在运行runme。”没有硬编码的短信?

21 个解决方案

#1


447  

me=`basename "$0"`

For reading through a symlink, which is usually not what you want (you usually don't want to confuse the user this way), try:

要阅读符号链接(通常不是您想要的),请尝试:

me="$(basename "$(test -L "$0" && readlink "$0" || echo "$0")")"

IMO, that'll produce confusing output. "I ran foo.sh, but it's saying I'm running bar.sh!? Must be a bug!" Besides, one of the purposes of having differently-named symlinks is to provide different functionality based on the name it's called as (think gzip and gunzip on some platforms).

在我看来,这会产生令人困惑的输出。“我跑foo。嘘,但这是说我在狂奔。嘘!?一定是个错误!”此外,拥有不同命名的符号链接的目的之一是基于它被称为的名称提供不同的功能(想想gzip和gunzip在某些平台上)。

#2


197  

# ------------- SCRIPT ------------- #

#!/bin/bash

echo
echo "# arguments called with ---->  ${@}     "
echo "# \$1 ---------------------->  $1       "
echo "# \$2 ---------------------->  $2       "
echo "# path to me --------------->  ${0}     "
echo "# parent path -------------->  ${0%/*}  "
echo "# my name ------------------>  ${0##*/} "
echo
exit

# ------------- CALLED ------------- #

# Notice on the next line, the first argument is called within double, 
# and single quotes, since it contains two words

$  /misc/shell_scripts/check_root/show_parms.sh "'hello there'" "'william'"

# ------------- RESULTS ------------- #

# arguments called with --->  'hello there' 'william'
# $1 ---------------------->  'hello there'
# $2 ---------------------->  'william'
# path to me -------------->  /misc/shell_scripts/check_root/show_parms.sh
# parent path ------------->  /misc/shell_scripts/check_root
# my name ----------------->  show_parms.sh

# ------------- END ------------- #

#3


154  

With bash >= 3 the following works:

关于bash >= 3的工作如下:

$ ./s
0 is: ./s
BASH_SOURCE is: ./s
$ . ./s
0 is: bash
BASH_SOURCE is: ./s

$ cat s
#!/bin/bash

printf '$0 is: %s\n$BASH_SOURCE is: %s\n' "$0" "$BASH_SOURCE"

#4


57  

If the script name has spaces in it, a more robust way is to use "$0" or "$(basename "$0")" - or on MacOS: "$(basename \"$0\")". This prevents the name from getting mangled or interpreted in any way. In general, it is good practice to always double-quote variable names in the shell.

如果脚本名称中有空格,则更可靠的方法是使用“$0”或“$(basename“$0”)”-或在MacOS上:“$(basename \“$0\”)”。这可以防止名称以任何方式被损坏或解释。通常,最好在shell中始终使用双引号变量名。

#5


54  

$BASH_SOURCE gives the correct answer when sourcing the script.

$BASH_SOURCE在寻找脚本时给出正确答案。

This however includes the path so to get the scripts filename only, use:

但是,这包括路径,以便仅获取脚本文件名,请使用:

$(basename $BASH_SOURCE) 

#6


21  

If you want it without the path then you would use ${0##*/}

如果你想要没有路径,你可以使用${0# */}

#7


19  

To answer Chris Conway, on Linux (at least) you would do this:

要回答Chris Conway,在Linux上(至少)你可以这么做:

echo $(basename $(readlink -nf $0))

readlink prints out the value of a symbolic link. If it isn't a symbolic link, it prints the file name. -n tells it to not print a newline. -f tells it to follow the link completely (if a symbolic link was a link to another link, it would resolve that one as well).

readlink打印符号链接的值。如果不是符号链接,则打印文件名。-n告诉它不打印换行符。-f让它完全跟随这个链接(如果一个符号链接是另一个链接的链接,它也会解析那个链接)。

#8


11  

These answers are correct for the cases they state but there is a still a problem if you run the script from another script using the 'source' keyword (so that it runs in the same shell). In this case, you get the $0 of the calling script. And in this case, I don't think it is possible to get the name of the script itself.

这些答案对于它们所描述的情况是正确的,但是如果您使用“source”关键字从另一个脚本运行脚本(以便在同一个shell中运行),仍然存在问题。在本例中,您将获得调用脚本的$0。在这种情况下,我认为不可能得到脚本本身的名称。

This is an edge case and should not be taken TOO seriously. If you run the script from another script directly (without 'source'), using $0 will work.

这是一个边缘情况,不应该太认真对待。如果您直接从另一个脚本(没有“source”)运行脚本,那么使用$0就可以了。

#9


11  

I've found this line to always work, regardless of whether the file is being sourced or run as a script.

我发现这一行始终有效,不管文件是作为源文件还是作为脚本运行。

echo "${BASH_SOURCE[${#BASH_SOURCE[@]} - 1]}"

If you want to follow symlinks use readlink on the path you get above, recursively or non-recursively.

如果您想遵循符号链接,请在上面的路径上使用readlink,递归的或非递归的。

The reason the one-liner works is explained by the use of the BASH_SOURCE environment variable and its associate FUNCNAME.

使用BASH_SOURCE环境变量及其关联函数名解释了一行代码工作的原因。

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]}.

数组变量,其成员为源文件名,定义了函数名数组变量中相应的shell函数名。shell函数${FUNCNAME[$i]}在文件${BASH_SOURCE[$i]}中定义,并从${BASH_SOURCE[$i+1]}中调用。

FUNCNAME

FUNCNAME

An array variable containing the names of all shell functions currently in the execution call stack. The element with index 0 is the name of any currently-executing shell function. The bottom-most element (the one with the highest index) is "main". This variable exists only when a shell function is executing. Assignments to FUNCNAME have no effect and return an error status. If FUNCNAME is unset, it loses its special properties, even if it is subsequently reset.

一个数组变量,包含当前执行调用堆栈中所有shell函数的名称。索引0的元素是当前执行的shell函数的名称。最底层的元素(具有最高索引的元素)是“main”。此变量仅在执行shell函数时存在。赋值函数没有效果,返回错误状态。如果函数名未被设置,它将失去它的特殊属性,即使它随后被重置。

This variable can be used with BASH_LINENO and BASH_SOURCE. Each element of FUNCNAME has corresponding elements in BASH_LINENO and BASH_SOURCE to describe the call stack. For instance, ${FUNCNAME[$i]} was called from the file ${BASH_SOURCE[$i+1]} at line number ${BASH_LINENO[$i]}. The caller builtin displays the current call stack using this information.

这个变量可以与BASH_LINENO和BASH_SOURCE一起使用。functionname的每个元素在BASH_LINENO和BASH_SOURCE中都有相应的元素来描述调用堆栈。例如,在line号${BASH_LINENO[$i]}中,从文件${BASH_SOURCE[$i+1]}中调用${FUNCNAME[$i]}。调用者builtin使用此信息显示当前调用堆栈。

[Source: Bash manual]

(来源:Bash手册)

#10


8  

Re: Tanktalus's (accepted) answer above, a slightly cleaner way is to use:

回复:Tanktalus(已被接受)的回答是:

me=$(readlink --canonicalize --no-newline $0)

If your script has been sourced from another bash script, you can use:

如果您的脚本来自另一个bash脚本,您可以使用:

me=$(readlink --canonicalize --no-newline $BASH_SOURCE)

I agree that it would be confusing to dereference symlinks if your objective is to provide feedback to the user, but there are occasions when you do need to get the canonical name to a script or other file, and this is the best way, imo.

我同意,如果您的目标是向用户提供反馈,那么取消引用符号链接将会令人困惑,但有时您确实需要将规范名获取到脚本或其他文件中,这是最好的方式,在imo上。

#11


6  

if your invoke shell script like

如果您的调用shell脚本喜欢

/home/mike/runme.sh

$0 is full name

美元0是全名

 /home/mike/runme.sh

basename $0 will get the base file name

basename $0将获得基本文件名

 runme.sh

and you need to put this basic name into a variable like

你需要把这个基本的名字放到一个变量中

filename=$(basename $0)

and add your additional text

并添加你的附加文本

echo "You are running $filename"

so your scripts like

所以您的脚本

/home/mike/runme.sh
#!/bin/bash 
filename=$(basename $0)
echo "You are running $filename"

#12


5  

You can use $0 to determine your script name (with full path) - to get the script name only you can trim that variable with

您可以使用$0来确定您的脚本名称(带有完整路径)——以获得只有您可以使用的脚本名称

basename $0

#13


5  

this="$(dirname "$(realpath "$BASH_SOURCE")")"

This resolves symbolic links (realpath does that), handles spaces (double quotes do this), and will find the current script name even when sourced (. ./myscript) or called by other scripts ($BASH_SOURCE handles that). After all that, it is good to save this in a environment variable for re-use or for easy copy elsewhere (this=)...

它解析符号链接(realpath实现了这一点),处理空格(双引号实现了这一点),并且即使在获取(. /myscript)或被其他脚本调用($BASH_SOURCE处理它)时也会找到当前的脚本名称。在此之后,最好将其保存在环境变量中,以便重用或方便在其他地方复制(this=)……

#14


3  

Since some comments asked about the filename without extension, here's an example how to accomplish that:

由于一些关于文件名的评论没有扩展,这里有一个如何实现的示例:

FileName=${0##*/}
FileNameWithoutExtension=${FileName%.*}

Enjoy!

享受吧!

#15


2  

Info thanks to Bill Hernandez. I added some preferences I'm adopting.

感谢Bill Hernandez。我添加了一些我正在采用的偏好。

#!/bin/bash
function Usage(){
    echo " Usage: show_parameters [ arg1 ][ arg2 ]"
}
[[ ${#2} -eq 0 ]] && Usage || {
    echo
    echo "# arguments called with ---->  ${@}     "
    echo "# \$1 ----------------------->  $1       "
    echo "# \$2 ----------------------->  $2       "
    echo "# path to me --------------->  ${0}     " | sed "s/$USER/\$USER/g"
    echo "# parent path -------------->  ${0%/*}  " | sed "s/$USER/\$USER/g"
    echo "# my name ------------------>  ${0##*/} "
    echo
}

Cheers

干杯

#16


2  

In bash you can get the script file name using $0. Generally $1, $2 etc are to access CLI arguments. Similarly $0 is to access the name which triggers the script(script file name).

在bash中,可以使用$0获取脚本文件名。通常$1、$2等等是用来访问CLI参数的。同样,$0将访问触发脚本(脚本文件名)的名称。

#!/bin/bash
echo "You are running $0"
...
...

If you invoke the script with path like /path/to/script.sh then $0 also will give the filename with path. In that case need to use $(basename $0) to get only script file name.

如果您使用/path/to/script这样的路径调用脚本。然后$0也会给出带有路径的文件名。在这种情况下,只需要使用$(basename $0)来获取脚本文件名。

#17


1  

echo "$(basename "`test -L ${BASH_SOURCE[0]} \
                   && readlink ${BASH_SOURCE[0]} \
                   || echo ${BASH_SOURCE[0]}`")"

#18


0  

echo "You are running $0"

echo "You are running $0"

#19


0  

$0 doesn't answer the question (as I understand it). A demonstration:

$0不能回答这个问题(据我理解)。一个示范:

$ cat script.sh
#! /bin/sh
echo `basename $0`
$ ./script.sh 
script.sh
$ ln script.sh linktoscript
$ ./linktoscript 
linktoscript

How does one get ./linktoscript to print out script.sh?

如何得到。/linktoscript来打印script.sh?

[EDIT] Per @ephemient in comments above, though the symbolic link thing may seem contrived, it is possible to fiddle with $0 such that it does not represent a filesystem resource. The OP is a bit ambiguous about what he wanted.

[EDIT] Per @ephemient在上面的评论中写道,尽管符号链接看起来有些做作,但是可以修改$0,这样它就不代表文件系统资源。OP对他想要什么有点模棱两可。

#20


0  

DIRECTORY=$(cd `dirname $0` && pwd)

I got the above from another Stack Overflow question, Can a Bash script tell what directory it's stored in?, but I think it's useful for this topic as well.

我从另一个堆栈溢出问题中得到了上面的内容,一个Bash脚本可以告诉它存储在哪个目录中吗?,但我认为这个话题也很有用。

#21


-5  

somthing like this?

这样事情吗?

export LC_ALL=en_US.UTF-8
#!/bin/bash
#!/bin/sh

#----------------------------------------------------------------------
start_trash(){
ver="htrash.sh v0.0.4"
$TRASH_DIR  # url to trash $MY_USER
$TRASH_SIZE # Show Trash Folder Size

echo "Would you like to empty Trash  [y/n]?"
read ans
if [ $ans = y -o $ans = Y -o $ans = yes -o $ans = Yes -o $ans = YES ]
then
echo "'yes'"
cd $TRASH_DIR && $EMPTY_TRASH
fi
if [ $ans = n -o $ans = N -o $ans = no -o $ans = No -o $ans = NO ]
then
echo "'no'"
fi
 return $TRUE
} 
#-----------------------------------------------------------------------

start_help(){
echo "HELP COMMANDS-----------------------------"
echo "htest www                 open a homepage "
echo "htest trash               empty trash     "
 return $TRUE
} #end Help
#-----------------------------------------------#

homepage=""

return $TRUE
} #end cpdebtemp

# -Case start
# if no command line arg given
# set val to Unknown
if [ -z $1 ]
then
  val="*** Unknown  ***"
elif [ -n $1 ]
then
# otherwise make first arg as val
  val=$1
fi
# use case statement to make decision for rental
case $val in
   "trash") start_trash ;;
   "help") start_help ;;
   "www") firefox $homepage ;;
   *) echo "Sorry, I can not get a $val   for you!";;
esac
# Case stop

#1


447  

me=`basename "$0"`

For reading through a symlink, which is usually not what you want (you usually don't want to confuse the user this way), try:

要阅读符号链接(通常不是您想要的),请尝试:

me="$(basename "$(test -L "$0" && readlink "$0" || echo "$0")")"

IMO, that'll produce confusing output. "I ran foo.sh, but it's saying I'm running bar.sh!? Must be a bug!" Besides, one of the purposes of having differently-named symlinks is to provide different functionality based on the name it's called as (think gzip and gunzip on some platforms).

在我看来,这会产生令人困惑的输出。“我跑foo。嘘,但这是说我在狂奔。嘘!?一定是个错误!”此外,拥有不同命名的符号链接的目的之一是基于它被称为的名称提供不同的功能(想想gzip和gunzip在某些平台上)。

#2


197  

# ------------- SCRIPT ------------- #

#!/bin/bash

echo
echo "# arguments called with ---->  ${@}     "
echo "# \$1 ---------------------->  $1       "
echo "# \$2 ---------------------->  $2       "
echo "# path to me --------------->  ${0}     "
echo "# parent path -------------->  ${0%/*}  "
echo "# my name ------------------>  ${0##*/} "
echo
exit

# ------------- CALLED ------------- #

# Notice on the next line, the first argument is called within double, 
# and single quotes, since it contains two words

$  /misc/shell_scripts/check_root/show_parms.sh "'hello there'" "'william'"

# ------------- RESULTS ------------- #

# arguments called with --->  'hello there' 'william'
# $1 ---------------------->  'hello there'
# $2 ---------------------->  'william'
# path to me -------------->  /misc/shell_scripts/check_root/show_parms.sh
# parent path ------------->  /misc/shell_scripts/check_root
# my name ----------------->  show_parms.sh

# ------------- END ------------- #

#3


154  

With bash >= 3 the following works:

关于bash >= 3的工作如下:

$ ./s
0 is: ./s
BASH_SOURCE is: ./s
$ . ./s
0 is: bash
BASH_SOURCE is: ./s

$ cat s
#!/bin/bash

printf '$0 is: %s\n$BASH_SOURCE is: %s\n' "$0" "$BASH_SOURCE"

#4


57  

If the script name has spaces in it, a more robust way is to use "$0" or "$(basename "$0")" - or on MacOS: "$(basename \"$0\")". This prevents the name from getting mangled or interpreted in any way. In general, it is good practice to always double-quote variable names in the shell.

如果脚本名称中有空格,则更可靠的方法是使用“$0”或“$(basename“$0”)”-或在MacOS上:“$(basename \“$0\”)”。这可以防止名称以任何方式被损坏或解释。通常,最好在shell中始终使用双引号变量名。

#5


54  

$BASH_SOURCE gives the correct answer when sourcing the script.

$BASH_SOURCE在寻找脚本时给出正确答案。

This however includes the path so to get the scripts filename only, use:

但是,这包括路径,以便仅获取脚本文件名,请使用:

$(basename $BASH_SOURCE) 

#6


21  

If you want it without the path then you would use ${0##*/}

如果你想要没有路径,你可以使用${0# */}

#7


19  

To answer Chris Conway, on Linux (at least) you would do this:

要回答Chris Conway,在Linux上(至少)你可以这么做:

echo $(basename $(readlink -nf $0))

readlink prints out the value of a symbolic link. If it isn't a symbolic link, it prints the file name. -n tells it to not print a newline. -f tells it to follow the link completely (if a symbolic link was a link to another link, it would resolve that one as well).

readlink打印符号链接的值。如果不是符号链接,则打印文件名。-n告诉它不打印换行符。-f让它完全跟随这个链接(如果一个符号链接是另一个链接的链接,它也会解析那个链接)。

#8


11  

These answers are correct for the cases they state but there is a still a problem if you run the script from another script using the 'source' keyword (so that it runs in the same shell). In this case, you get the $0 of the calling script. And in this case, I don't think it is possible to get the name of the script itself.

这些答案对于它们所描述的情况是正确的,但是如果您使用“source”关键字从另一个脚本运行脚本(以便在同一个shell中运行),仍然存在问题。在本例中,您将获得调用脚本的$0。在这种情况下,我认为不可能得到脚本本身的名称。

This is an edge case and should not be taken TOO seriously. If you run the script from another script directly (without 'source'), using $0 will work.

这是一个边缘情况,不应该太认真对待。如果您直接从另一个脚本(没有“source”)运行脚本,那么使用$0就可以了。

#9


11  

I've found this line to always work, regardless of whether the file is being sourced or run as a script.

我发现这一行始终有效,不管文件是作为源文件还是作为脚本运行。

echo "${BASH_SOURCE[${#BASH_SOURCE[@]} - 1]}"

If you want to follow symlinks use readlink on the path you get above, recursively or non-recursively.

如果您想遵循符号链接,请在上面的路径上使用readlink,递归的或非递归的。

The reason the one-liner works is explained by the use of the BASH_SOURCE environment variable and its associate FUNCNAME.

使用BASH_SOURCE环境变量及其关联函数名解释了一行代码工作的原因。

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]}.

数组变量,其成员为源文件名,定义了函数名数组变量中相应的shell函数名。shell函数${FUNCNAME[$i]}在文件${BASH_SOURCE[$i]}中定义,并从${BASH_SOURCE[$i+1]}中调用。

FUNCNAME

FUNCNAME

An array variable containing the names of all shell functions currently in the execution call stack. The element with index 0 is the name of any currently-executing shell function. The bottom-most element (the one with the highest index) is "main". This variable exists only when a shell function is executing. Assignments to FUNCNAME have no effect and return an error status. If FUNCNAME is unset, it loses its special properties, even if it is subsequently reset.

一个数组变量,包含当前执行调用堆栈中所有shell函数的名称。索引0的元素是当前执行的shell函数的名称。最底层的元素(具有最高索引的元素)是“main”。此变量仅在执行shell函数时存在。赋值函数没有效果,返回错误状态。如果函数名未被设置,它将失去它的特殊属性,即使它随后被重置。

This variable can be used with BASH_LINENO and BASH_SOURCE. Each element of FUNCNAME has corresponding elements in BASH_LINENO and BASH_SOURCE to describe the call stack. For instance, ${FUNCNAME[$i]} was called from the file ${BASH_SOURCE[$i+1]} at line number ${BASH_LINENO[$i]}. The caller builtin displays the current call stack using this information.

这个变量可以与BASH_LINENO和BASH_SOURCE一起使用。functionname的每个元素在BASH_LINENO和BASH_SOURCE中都有相应的元素来描述调用堆栈。例如,在line号${BASH_LINENO[$i]}中,从文件${BASH_SOURCE[$i+1]}中调用${FUNCNAME[$i]}。调用者builtin使用此信息显示当前调用堆栈。

[Source: Bash manual]

(来源:Bash手册)

#10


8  

Re: Tanktalus's (accepted) answer above, a slightly cleaner way is to use:

回复:Tanktalus(已被接受)的回答是:

me=$(readlink --canonicalize --no-newline $0)

If your script has been sourced from another bash script, you can use:

如果您的脚本来自另一个bash脚本,您可以使用:

me=$(readlink --canonicalize --no-newline $BASH_SOURCE)

I agree that it would be confusing to dereference symlinks if your objective is to provide feedback to the user, but there are occasions when you do need to get the canonical name to a script or other file, and this is the best way, imo.

我同意,如果您的目标是向用户提供反馈,那么取消引用符号链接将会令人困惑,但有时您确实需要将规范名获取到脚本或其他文件中,这是最好的方式,在imo上。

#11


6  

if your invoke shell script like

如果您的调用shell脚本喜欢

/home/mike/runme.sh

$0 is full name

美元0是全名

 /home/mike/runme.sh

basename $0 will get the base file name

basename $0将获得基本文件名

 runme.sh

and you need to put this basic name into a variable like

你需要把这个基本的名字放到一个变量中

filename=$(basename $0)

and add your additional text

并添加你的附加文本

echo "You are running $filename"

so your scripts like

所以您的脚本

/home/mike/runme.sh
#!/bin/bash 
filename=$(basename $0)
echo "You are running $filename"

#12


5  

You can use $0 to determine your script name (with full path) - to get the script name only you can trim that variable with

您可以使用$0来确定您的脚本名称(带有完整路径)——以获得只有您可以使用的脚本名称

basename $0

#13


5  

this="$(dirname "$(realpath "$BASH_SOURCE")")"

This resolves symbolic links (realpath does that), handles spaces (double quotes do this), and will find the current script name even when sourced (. ./myscript) or called by other scripts ($BASH_SOURCE handles that). After all that, it is good to save this in a environment variable for re-use or for easy copy elsewhere (this=)...

它解析符号链接(realpath实现了这一点),处理空格(双引号实现了这一点),并且即使在获取(. /myscript)或被其他脚本调用($BASH_SOURCE处理它)时也会找到当前的脚本名称。在此之后,最好将其保存在环境变量中,以便重用或方便在其他地方复制(this=)……

#14


3  

Since some comments asked about the filename without extension, here's an example how to accomplish that:

由于一些关于文件名的评论没有扩展,这里有一个如何实现的示例:

FileName=${0##*/}
FileNameWithoutExtension=${FileName%.*}

Enjoy!

享受吧!

#15


2  

Info thanks to Bill Hernandez. I added some preferences I'm adopting.

感谢Bill Hernandez。我添加了一些我正在采用的偏好。

#!/bin/bash
function Usage(){
    echo " Usage: show_parameters [ arg1 ][ arg2 ]"
}
[[ ${#2} -eq 0 ]] && Usage || {
    echo
    echo "# arguments called with ---->  ${@}     "
    echo "# \$1 ----------------------->  $1       "
    echo "# \$2 ----------------------->  $2       "
    echo "# path to me --------------->  ${0}     " | sed "s/$USER/\$USER/g"
    echo "# parent path -------------->  ${0%/*}  " | sed "s/$USER/\$USER/g"
    echo "# my name ------------------>  ${0##*/} "
    echo
}

Cheers

干杯

#16


2  

In bash you can get the script file name using $0. Generally $1, $2 etc are to access CLI arguments. Similarly $0 is to access the name which triggers the script(script file name).

在bash中,可以使用$0获取脚本文件名。通常$1、$2等等是用来访问CLI参数的。同样,$0将访问触发脚本(脚本文件名)的名称。

#!/bin/bash
echo "You are running $0"
...
...

If you invoke the script with path like /path/to/script.sh then $0 also will give the filename with path. In that case need to use $(basename $0) to get only script file name.

如果您使用/path/to/script这样的路径调用脚本。然后$0也会给出带有路径的文件名。在这种情况下,只需要使用$(basename $0)来获取脚本文件名。

#17


1  

echo "$(basename "`test -L ${BASH_SOURCE[0]} \
                   && readlink ${BASH_SOURCE[0]} \
                   || echo ${BASH_SOURCE[0]}`")"

#18


0  

echo "You are running $0"

echo "You are running $0"

#19


0  

$0 doesn't answer the question (as I understand it). A demonstration:

$0不能回答这个问题(据我理解)。一个示范:

$ cat script.sh
#! /bin/sh
echo `basename $0`
$ ./script.sh 
script.sh
$ ln script.sh linktoscript
$ ./linktoscript 
linktoscript

How does one get ./linktoscript to print out script.sh?

如何得到。/linktoscript来打印script.sh?

[EDIT] Per @ephemient in comments above, though the symbolic link thing may seem contrived, it is possible to fiddle with $0 such that it does not represent a filesystem resource. The OP is a bit ambiguous about what he wanted.

[EDIT] Per @ephemient在上面的评论中写道,尽管符号链接看起来有些做作,但是可以修改$0,这样它就不代表文件系统资源。OP对他想要什么有点模棱两可。

#20


0  

DIRECTORY=$(cd `dirname $0` && pwd)

I got the above from another Stack Overflow question, Can a Bash script tell what directory it's stored in?, but I think it's useful for this topic as well.

我从另一个堆栈溢出问题中得到了上面的内容,一个Bash脚本可以告诉它存储在哪个目录中吗?,但我认为这个话题也很有用。

#21


-5  

somthing like this?

这样事情吗?

export LC_ALL=en_US.UTF-8
#!/bin/bash
#!/bin/sh

#----------------------------------------------------------------------
start_trash(){
ver="htrash.sh v0.0.4"
$TRASH_DIR  # url to trash $MY_USER
$TRASH_SIZE # Show Trash Folder Size

echo "Would you like to empty Trash  [y/n]?"
read ans
if [ $ans = y -o $ans = Y -o $ans = yes -o $ans = Yes -o $ans = YES ]
then
echo "'yes'"
cd $TRASH_DIR && $EMPTY_TRASH
fi
if [ $ans = n -o $ans = N -o $ans = no -o $ans = No -o $ans = NO ]
then
echo "'no'"
fi
 return $TRUE
} 
#-----------------------------------------------------------------------

start_help(){
echo "HELP COMMANDS-----------------------------"
echo "htest www                 open a homepage "
echo "htest trash               empty trash     "
 return $TRUE
} #end Help
#-----------------------------------------------#

homepage=""

return $TRUE
} #end cpdebtemp

# -Case start
# if no command line arg given
# set val to Unknown
if [ -z $1 ]
then
  val="*** Unknown  ***"
elif [ -n $1 ]
then
# otherwise make first arg as val
  val=$1
fi
# use case statement to make decision for rental
case $val in
   "trash") start_trash ;;
   "help") start_help ;;
   "www") firefox $homepage ;;
   *) echo "Sorry, I can not get a $val   for you!";;
esac
# Case stop