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 
$
相关推荐
winds~41 分钟前
【git】 撤销revert一次commit中的某几个文件
linux·c++
iY_n1 小时前
Linux网络基础
linux·网络·arm开发
硅上观道1 小时前
打造 NixOS 开发环境 (1):为什么选择 Nix
linux
phoenix09812 小时前
Linux入门DAY27
linux·运维·服务器
xw53 小时前
免费的个人网站托管-PinMe篇
服务器·前端
♞沉寂4 小时前
信号以及共享内存
linux·c语言·开发语言
egoist20234 小时前
【Linux仓库】进程创建与进程终止【进程·柒】
linux·运维·服务器·进程创建·写时拷贝·进程终止
大锦终4 小时前
【Linux】文件系统
linux·服务器·c++
Kyln.Wu5 小时前
【python实用小脚本-190】Python一键删除PDF任意页:输入页码秒出干净文件——再也不用在线裁剪排队
服务器·python·pdf