乐闻世界logo
搜索文章和话题

How do I know the script file name in a Bash script?

1个答案

1

Obtaining the current script's filename in a Bash script is straightforward. We can use the built-in variable $0 to retrieve the name of the current script. This variable contains the command used to launch the script, which is typically the script's path.

For example, suppose we have a script named script.sh. We can add the following code to print the script filename within the script:

bash
#!/bin/bash echo "Script name: $0"

When you run this script, it will output something like:

shell
Script name: ./script.sh

If you only want to obtain the filename without the path, you can use the basename command to extract the filename:

bash
#!/bin/bash script_name=$(basename "$0") echo "Script name: $script_name"

This code uses basename "$0" to extract the filename from $0, even if $0 includes path information. When you run this script, the output will be:

shell
Script name: script.sh

This approach is particularly useful for logging, generating output files with specific filenames, or when the script needs to reference its own filename.

2024年8月14日 18:04 回复

你的答案