linux,shell脚本中获取脚本的名字,使用脚本的名字。

需求描述

  写shell脚本的过程中,有时会需要获取脚本的名字,比如,有的时候,脚本

  中会有usage()这种函数,可能就会用到脚本的名字。

实现方法

  shell脚本中,通过使用$0就可以获取到脚本的名字或者说脚本本身。

操作过程

1.通过以下的脚本写了一个脚本的使用函数usage()

#!/bin/bash

#function usage means how to use this script.
usage()
        {
                echo "Usage: $0 process_name1"
                echo "for example $0 mysqld"
        }

        #if no parameter is passed to script then show how to use.
        if [ $# -eq 0 ];
        then
                usage
                exit
        fi

备注:以上脚本的意思就是,如果脚本执行时,脚本的参数是0个,那么就调用usage函数,然后退出。

2.执行并且测试,是否会输出脚本的名字

[oracle@standby ~]$ ./ts01.sh 
Usage: ./ts01.sh process_name1
for example ./ts01.sh mysqld

 说明:执行测试脚本,没有给任何的参数即脚本参数的数量是0个,那么就调用了usage()函数,此时说出了脚本的名字或者说$0位置的内容,此处输出的是

  ./ts01.sh也就是$0

或者,通过sh命令进行调用脚本

[oracle@standby ~]$ sh ts01.sh 
Usage: ts01.sh process_name1
for example ts01.sh mysqld

备注:输出的正好是ts01.sh

或者通过绝对路径的方式调用脚本

[oracle@standby ~]$ /home/oracle/ts01.sh 
Usage: /home/oracle/ts01.sh process_name1
for example /home/oracle/ts01.sh mysqld 

备注:输出的绝对路径加上脚本的名字。

小结

  通过以上测试可以知道,$0就是命令行中写的是什么输出就是什么,但是,通过sh命令调用脚本,就是脚本名字本身了,不带./也不带路径。

  主要看脚本的调用方式是什么。

文档创建时间:2018年3月14日10:27:54

原文地址:https://www.cnblogs.com/chuanzhang053/p/8565769.html