shell_38.Linux读取脚本名

读取脚本名

(1)示例

复制代码
$ cat positional0.sh 
#!/bin/bash 
# Handling the $0 command-line parameter 
#
echo This script name is $0. 
exit 
$ 
$ bash positional0.sh 
This script name is positional0.sh. 
$

(2)如果使用另一个命令来运行 shell 脚本,则命令名会和脚本名混在一起,出现在位置变量$0 中:

复制代码
$ ./positional0.sh 
This script name is ./positional0.sh. 
$

那么位置变量$0 就会包含整个路径:

复制代码
$ $HOME/scripts/positional0.sh 
This script name is /home/christine/scripts/positional0.sh. 
$

(3)如果你编写的脚本中只打算使用脚本名,那就得做点儿额外工作,剥离脚本的运行路径。好在有个方便的小命令可以帮到我们。

basename 命令可以返回不包含路径的脚本名:

复制代码
$ cat posbasename.sh 
#!/bin/bash 
# Using basename with the $0 command-line parameter 
# 
name=$(basename $0) 
# 
echo This script name is $name. 
exit 
$ 
$ ./posbasename.sh 
This script name is posbasename.sh. 
$

(4)可以使用此技术编写一个脚本,生成能标识运行时间的日志消息:

复制代码
$ cat checksystem.sh 
#!/bin/bash 
# Using the $0 command-line parameter in messages 
# 
scriptname=$(basename $0) 
# 
echo The $scriptname ran at $(date) >> $HOME/scripttrack.log 
exit 
$ 
$ ./checksystem.sh
$ cat $HOME/scripttrack.log
The checksystem.sh ran at Thu 04 Jun 2020 10:01:53 AM EDT 
$
相关推荐
A小辣椒2 小时前
TShark:基础知识
linux
AlfredZhao4 小时前
OCI 明明分配了 200G 系统盘,为什么 df 只看到 30G?
linux·oci
AlfredZhao19 小时前
vi 删除指定范围的行,不用再反复按 dd
linux·vi
用户9718356334661 天前
银河麒麟 KY10 申威(SW64) 安装 nginx-1.16.1-2.p01.ky10.sw_64.rpm 详细步骤
linux
猪脚踏浪1 天前
linux 拷贝文件或目录到指定的位置
linux
大树882 天前
金刚石散热越强,管路越先见顶
大数据·运维·服务器·人工智能·ai
摇滚侠2 天前
Linux CentOS7 rpm 安装 MySQL 5.7
linux·运维·mysql
霸道流氓气质2 天前
领域驱动设计(DDD)在 Spring Boot 微服务中的实践指南
运维·spring boot·微服务
bush42 天前
嵌入式linux学习记录十四、术语
linux·嵌入式
载数而行5202 天前
Linux 11 动态监控指令top
linux