加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

bash参数解析

(2020-04-17 17:10:20)
标签:

bash

参数

解析

分类: linux
1.特殊特殊变量
#!/bin/bash
# file test.sh

echo $0    # 当前脚本的文件名(间接运行时还包括绝对路径)。
echo $1    # 传递给脚本或函数的参数。n 是一个数字,表示第几个参数。例如,第一个参数是 $1 。
echo $#    # 传递给脚本或函数的参数个数。
echo $*    # 传递给脚本或函数的所有参数。
echo $@    # 传递给脚本或函数的所有参数。被双引号 (" ") 包含时,与 $* 不同,下面将会讲到。
echo $?    # 上个命令的退出状态,或函数的返回值。
echo $$    # 当前 Shell 进程 ID。对于 Shell 脚本,就是这些脚本所在的进程 ID。
echo $_    # 上一个命令的最后一个参数
echo $!    # 后台运行的最后一个进程的 ID 号

root@VM-130-124-debian:~/temp# sh test.sh abc def 123
test.sh
abc
3
abc def 123
abc def 123
0
20775
/bin/sh

$* 和 $@ 都表示传递给函数或脚本的所有参数,不被双引号 ("") 包含时,都以"$1""$2" … "$n" 的形式输出所有参数。
但是当它们被双引号 ("") 包含时,"$*"会将所有的参数作为一个整体,以"$1 $2 … $n"的形式输出所有参数;"$@"会将各个参数分开,以"$1""$2" … "$n" 的形式输出所有参数。


2.依次分割输入参数
#!/bin/bash
# file params.sh

printf "The complete list is %s\n" "$$"
printf "The complete list is %s\n" "$!"
printf "The complete list is %s\n" "$?"
printf "The complete list is %s\n" "$*"
printf "The complete list is %s\n" "$@"
printf "The complete list is %s\n" "$#"
printf "The complete list is %s\n" "$0"
printf "The complete list is %s\n" "$1"
printf "The complete list is %s\n" "$2"


root@VM-130-124-debian:~/temp# bash params.sh 123456 QQ
The complete list is 14961
The complete list is 
The complete list is 0
The complete list is 123456 QQ
The complete list is 123456
The complete list is QQ
The complete list is 2
The complete list is params.sh
The complete list is 123456
The complete list is QQ

3.getopt 处理参数
#!/bin/bash
# file proxychains4.sh

GETOPTOUT=`getopt ab:c:d "$@"`
    set -- $GETOPTOUT
    while [ -n "$1" ]
    do
    case $1 in
        -a)
            echo "发现 -a 选项"
            ;;
        -b)
            echo "发现 -b 选项"
            echo "-b 选项的参数值是:$2"
            shift
            ;;
        -c)
            echo "发现 -c 选项"
            echo "-c 选项的参数值是:$2"
            shift
            ;;
        -d)
            echo "发现 -d 选项"
            ;;
        --)
            shift
            break
            ;;
         *)
             echo "未知选项:"$1""
            ;;
    esac
    shift
    done
    
root@VM-130-124-debian:~/temp# sh proxychains4.sh -a -b t2 -c t3 -d
发现 -a 选项
发现 -b 选项
-b 选项的参数值是:t2
发现 -c 选项
-c 选项的参数值是:t3
发现 -d 选项

getopt ab:c:d "$@" 中的 abcd 分别代表四个选项,后面带有冒号的表示选项需要参数值

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有