在bash中设置变量名称的变量(para $ i = ... give" command not found")

时间:2016-09-12 15:58:20

标签: bash shell

我想将三个参数传递给一个脚本,前两个数字和第三个任意一个字符,Buut当我运行脚本时它说 command not found ,即使该值已被分配。我已附上下面的代码和图片。enter image description here 这是我的代码,

#!/bin/bash
if [ $# -lt 3 ]
then
echo "insufficient argument"
for((i=$#+1;i<4;i=$i+1))
do
read -p "enter $i parameter: " x
para$i=x
done
fi

2 个答案:

答案 0 :(得分:0)

请参阅处理名为process_date的参数的示例 这个脚本接受参数如下:

some_sh_script.sh -process_date=01/01/2016

脚本:

process_date=""

while test "$1" != "" ; do

    # Test argument syntax e.g. -someName=someValue or help operators
    if [[ $1 != -*=*  &&  $1 != -h  &&  $1 != -help ]]
        then
            echo "Error in $0 - $1 - Argument syntax invalid."
            usage
        exit 1
    fi
    # END Test argument syntax

    # Split argument name & value by `=` delimiter
    paramName=`echo $1 | cut -d '=' -f1`
    paramVal=`echo $1 | cut -d '=' -f2`

    case $paramName in          

        -process_date)  
                process_date=$paramVal
            ;;


        #User help parameter
        -help|-h)
                usage
                exit 0
        ;;
        -*)
                echo "No such option $1"
                usage
                exit 1
        ;;
    esac    

    #parse next argument
    shift
done

答案 1 :(得分:0)

这不是有效的作业:

para$i=x

由于你的shell是bash,你可以改为:

# bash 3.1 or higher
printf -v "para$i" %s "$x"

...或...

# bash 4.3 or higher; works with arrays and other tricky cases too.
declare -n para="para$i"
para=$x
unset -n para

...或...

# any POSIX shell
# be very careful about the quoting; only safe if $x is quoted and $i is a controlled value
eval "para$i=\$x"

有关详细信息,请参阅the BashFAQ #6 section on indirect assignment