首页 > 解决方案 > 使用 OPTARG 作为 shell 脚本中的变量,无论参数的顺序如何

问题描述

假设我有一个像这样的脚本:(我们称之为 test.sh)

#!/bin/sh

function php() {
    printf "The rhost is ${RHOST} and the lport is ${LPORT}"
}

while getopts "hr:l:s:" arg; do
    case $arg in
        h)
            printf "Usage\n"
        ;;

        r)
            RHOST=$OPTARG
        ;;

        l)
            LPORT=$OPTARG
        ;;

        s)
            SHELL=$OPTARG

            if [[ "$SHELL" == "php" ]] || [[ "$SHELL" == "PHP" ]] ; then
                php

            fi
       ;;
    esac
done

如果我像“test.sh -r 10 -l 4 -s php”这样运行我的脚本

我的脚本会按照我的意愿执行...

但是,如果我像“test.sh -s php -r 10 -l 4”一样运行它

rhost 和 lport 变量永远不会进入 php 函数。我意识到这是因为它首先被调用。但是,我的问题是,如何编写脚本,以便无论参数运行方式的顺序如何,我仍然可以使用 rhost 和 lport 作为变量?

我也尝试过使用 shift,但我猜这不是答案,或者我将 shift 命令放在错误的位置。

标签: bashsh

解决方案


将“if”逻辑移出开关/案例:

#!/bin/sh
function php() {
    printf "The rhost is ${RHOST} and the lport is ${LPORT}"
}

while getopts "hr:l:s:" arg; do
    case $arg in
        h)
            printf "Usage\n"
        ;;

        r)
            RHOST=$OPTARG
        ;;

        l)
            LPORT=$OPTARG
        ;;

        s)
            SHELL=$OPTARG         
       ;;
    esac    
done

if [[ "$SHELL" == "php" ]] || [[ "$SHELL" == "PHP" ]] 
then
   php
fi

推荐阅读