如何更改用户输入变量?

时间:2015-02-08 17:53:50

标签: bash variables user-input

这就是我所拥有的

echo "Please select an Environment "

PS3="Please enter 1-6: "
select env in dev qa test staging production quit
do
    case $env in
        dev|qa|test|staging|production|quit)
            break
            ;;
        *)
            break
            ;;
    esac
done

echo $env

我想要的是当有人选择和env变量时我想翻译它。

例如,Production将转换为$ env = portal

2 个答案:

答案 0 :(得分:1)

脚本:

#!/usr/bin/env bash

declare -ar OPTIONS=('dev' 'qa' 'test' 'quit')
PS3="Please enter 1-${#OPTIONS[@]}: "

select OPTION in "${OPTIONS[@]}"
do
    case ${OPTION} in
        'dev')
            env='Development environment'
            break
            ;;
        'qa')
            env='Quality Assurance environment'
            break
            ;;
        'test')
            env='Test environment'
            break
            ;;
        'quit')
            echo 'See ya' && exit 0
            ;;
        *) echo 'invalid option';;
    esac
done

echo "env = ${env}"

exit 0

使用示例:

$ ./so_q28397293.sh
1) dev
2) qa
3) test
4) quit
Please enter 1-4: 1
env = Development environment

$ ./so_q28397293.sh
1) dev
2) qa
3) test
4) quit
Please enter 1-4: 5
invalid option
Please enter 1-4: 4
See ya
$

这是你想要的吗?


不要忘记test是Bash中的保留字(这就是我引用它的原因):

$ bash -c "help test"
test: test [expr]
    Evaluate conditional expression.

    Exits with a status of 0 (true) or 1 (false) depending on
    the evaluation of EXPR.  Expressions may be unary or binary.  Unary
    expressions are often used to examine the status of a file.  There
    are string operators and numeric comparison operators as well.
    ...

答案 1 :(得分:0)

您可以尝试:

echo "Please select an Environment "

echo -n "Please enter 1-6: "
read ARG
case $ARG in
    1) ENV="dev" ;;
    2) ENV="qa" ;;
    #etc
esac

echo $env