Bash Shell passing variable number of arguments

2019-08-15 18:08发布

I am working creating a bash shell framework where I need to pass variable number of arguments from one script to another.

Script1.sh

#!/bin/bash
vOut=`sudo -u execuser script2.sh $1 $2 $3`

Script2.sh

ActualScriptName="$2"
Host="$1"
Args="$3"
vOut=`$ActualScriptName -H${HOST} "$Args"

ActualScript3.sh

#!/bin/bash
while getopts ":H:s:e:" OPTION
do
    case $OPTION in
    T)
        HOST=${OPTARG}
        ;;
    s)
        START_TIME=${OPTARG}
        ;;
    e)
        END_TIME=${OPTARG}
        ;;
    ?)
        usage
        exit
        ;;
    esac
done
echo HOST=$HOST
echo START_TIME=$START_TIME
echo END_TIME=$END_TIME

Now, when I am calling script1.sh:

script1.sh 10.1.1.1 ActualScript1.sh "-s='2015-09-20 02:00'  -e='2015-09-20 02:30'"

I am getting output as:

HOST=10.1.1.1
START_TIME='2015-09-20 02:00' -e'2015-09-20 02:30' 
END_TIME=

How can I pass this variable number of arguments from script1 for ActualScript1.sh?

标签: linux shell
1条回答
Root(大扎)
2楼-- · 2019-08-15 18:54

You should use "$@" for passing around all the arguments from one script to another and use shift to move positional arguments.

You can have these scripts like this:

script1.sh:

#!/bin/bash
./script2.sh "$@"

script2.sh:

Host="$1"
ActualScriptName="$2"
shift 2

"$ActualScriptName" -H"$Host" "$@"

script3.sh:

#!/bin/bash
while getopts ":H:s:e:" OPTION
do
        case $OPTION in
        H)
        HOST=${OPTARG}
        ;;
        s)
        START_TIME=${OPTARG}
        ;;
        e)
        END_TIME=${OPTARG}
        ;;
        ?)
        echo "usage"
        #exit
        ;;
        esac
done

echo HOST="$HOST"
echo START_TIME="$START_TIME"
echo END_TIME="$END_TIME"
查看更多
登录 后发表回答