如何更改用户输入变量?

How do I change a user input variable?

这是我的

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

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

例如 Production 将转换为 $env=portal

脚本:

#!/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.
    ...

你可以试试:

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