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 
$
相关推荐
BugShare15 分钟前
飞牛NAS笔记本盒盖不休眠
linux
红球yyds18 分钟前
haproxy介绍及部署
linux·运维·云原生
切糕师学AI39 分钟前
NAT (Network Address Translation,网络地址转换)
运维·服务器·网络
x-cmd1 小时前
Browser-Use:用自然语言控制浏览器,告别脆弱的自动化脚本
运维·ai·自动化·agent·浏览器·x-cmd
AC赳赳老秦1 小时前
软件组件自动化的革命:DeepSeek 引领高效开发新时代
运维·人工智能·算法·云原生·maven·devops·deepseek
之歆1 小时前
LVS 负载均衡完全指南
运维·负载均衡·lvs
Web极客码1 小时前
用 SSH Key 认证提升文件传输安全:SFTP/SSH 加固实战(适合站点运维与外贸站)
运维·安全·ssh
zhojiew2 小时前
在中国区EKS集群使用 kgateway 代理 Lambda 函数的实践过程
运维·envoy
Channing Lewis2 小时前
为什么部署的项目会耗尽系统句柄
服务器
daad7773 小时前
schedule_fair
linux