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 
$
相关推荐
Le_ee2 分钟前
Apache2
服务器·网络安全·apache·web
wanhengidc4 分钟前
云手机 手游专用虚拟手机
运维·服务器·安全·游戏·智能手机
檀越剑指大厂11 分钟前
【Linux系列】Vim 中删除当前光标到行尾
linux·运维·vim
菠萝吹雪ing24 分钟前
GUI 自动化与接口自动化:概念、差异与协同落地
运维·笔记·程序人生·自动化·接口测试·gui测试
FIavor.25 分钟前
我发送给Apifox是http://localhost:9002/goods/getByUserName?name=张三 为什么会是500哪里错了?
java·服务器·网络协议·http
qiuiuiu4131 小时前
正点原子RK3568学习日志-编译第一个驱动程序helloworld
linux·c语言·开发语言·单片机
周之鸥1 小时前
从零部署 Astro 静态网站到云服务器(含 HTTPS 一键配置)
运维·服务器·ubuntu·http·https·astro
林开落L1 小时前
线程进阶:线程池、单例模式与线程安全深度解析
linux·安全·单例模式·线程池
Microsoft Word2 小时前
跨平台向量库:Linux & Windows 上一条龙部署 PostgreSQL 向量扩展
linux·windows·postgresql
noravinsc2 小时前
centos如何做的时间同步
linux·运维·centos