zoukankan      html  css  js  c++  java
  • shell编程学习笔记(五):Shell中脚本的参数

    在执行Shell脚本的时候,可以在执行时带上参数,相当于传递参数给脚本,下面我们看一下怎么使用这个参数

    以下蓝色字体部分为Linux命令,红色字体的内容为输出的内容:

    # cd /opt/scripts

    # vim script05.sh

    开始编写script05.sh的脚本,脚本内容为:

    1 #! /bin/sh
    2 echo "$# 个参数"
    3 echo "参数内容:$@"
    4 echo "第一个参数内容:$1"
    5 
    6 ps -ef|grep $1

    # chmod +x script05.sh

    # ./script05.sh tomcat

    1 个参数
    参数内容:tomcat
    第一个参数内容:tomcat
    root 3618 1 0 03:12 pts/0 00:01:08 /opt/software/jdk1.6.0_45/bin/java -Djava.util.logging.config.file=/opt/software/apache-tomcat-7.0.93/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djdk.tls.ephemeralDHKeySize=2048 -Dignore.endorsed.dirs= -classpath /opt/software/apache-tomcat-7.0.93/bin/bootstrap.jar:/opt/software/apache-tomcat-7.0.93/bin/tomcat-juli.jar -Dcatalina.base=/opt/software/apache-tomcat-7.0.93 -Dcatalina.home=/opt/software/apache-tomcat-7.0.93 -Djava.io.tmpdir=/opt/software/apache-tomcat-7.0.93/temp org.apache.catalina.startup.Bootstrap start
    root 4934 4735 0 06:42 pts/2 00:00:00 /bin/sh ./script05.sh tomcat
    root 4936 4934 0 06:42 pts/2 00:00:00 grep tomcat

    我来解释一下上面的脚本内容:

    第2行中的$#是指传入参数的参数数量

    第3行中的$@是指显示所有传入参数的内容

    第4行中的$1是指第1个参数的内容,以此类推,$n是指第n个参数的内容

    第6行中的ps -ef|grep $1会把我输入的参数tomcat替换到这个$1的位置,执行ps -ef|grep tomcat这个linux指令,用来显示tomcat进程的状态

    shell编程中的参数引用: 

    参数处理说明
    $# 传递到脚本的参数个数
    $* 以一个单字符串显示所有向脚本传递的参数。
    如"$*"用「"」括起来的情况、以"$1 $2 … $n"的形式输出所有参数。
    $$ 脚本运行的当前进程ID号
    $! 后台运行的最后一个进程的ID号
    $@ 与$*相同,但是使用时加引号,并在引号中返回每个参数。
    如"$@"用「"」括起来的情况、以"$1" "$2" … "$n" 的形式输出所有参数。
    $- 显示Shell使用的当前选项,与set命令功能相同。
    $? 显示最后命令的退出状态。0表示没有错误,其他任何值表明有错误。
  • 相关阅读:
    git --解决fatal: Not a git repository
    Linux --常见Linux目录名称
    Python--oop面向对象的学习1
    python --集合set的学习
    python --error整理(不定时更新)
    vue自定义指令获取焦点及过滤器修改时间
    解决GitHub push项目——Push failed: Unable to access 'https://********.git/': Failed to connect to 127.0.0.1 port 1080: Connection refused
    vue项目报错,解决Module build failed: Error: Cannot find module 'node-sass' 问题
    webpack打包过程及开发过程
    安装webpack的流程及注意事项
  • 原文地址:https://www.cnblogs.com/modou/p/10441041.html
Copyright © 2011-2022 走看看