Shell脚本检查无输入并设置变量

时间:2021-12-31 11:45:43

I have trouble with a bash script. I want the user to state the username and if not set, set it automatically to root.

我在使用bash脚本时遇到问题。我希望用户说明用户名,如果没有设置,请将其自动设置为root。

#!/bin/bash
printf "MySQL User: (root)"
read MYSQLUSER
if [[ "$MYSQLUSER" == "" ]]; then
    set MYSQLUSER = "root"
fi

I've tried various syntaxes and shells but the if statement is always being ignored. This should be run on a Mac. Thanks for your help!

我尝试了各种语法和shell,但if语句总是被忽略。这应该在Mac上运行。谢谢你的帮助!

2 个解决方案

#1


Just use:

your_var=${MYSQLUSER:-root}

The ${var:-$DEFAULT} means: If var not set or is empty, evaluate expression as $DEFAULT *.

$ {var: - $ DEFAULT}表示:如果var未设置或为空,则将表达式计算为$ DEFAULT *。


All together, I would rewrite the script to something like:

总而言之,我会将脚本重写为:

#!/bin/bash
printf "MySQL User: (root) "
read MYSQLUSER
MYSQLUSER=${MYSQLUSER:-root}
echo "mysqluser: $MYSQLUSER"

See its execution with different behaviours:

查看具有不同行为的执行情况:

$ ./a.sh 
MySQL User: (root)              #just pressed intro
mysqluser: root
$ ./a.sh 
MySQL User: (root) hello        #I wrote 'hello'
mysqluser: hello

#2


A common idiom is to use the command

常用的习惯用法是使用该命令

: ${MYSQLUSR:=root}

which assigns the value root to MYSQLUSER if it does not already have a non-null value.

如果值尚未具有非空值,则将值赋给MYSQLUSER。

(: is the do-nothing command; the arguments are evaluated, then ignored. It's the evaluation of the := expansion that actually sets the value of MYSQLUSER.)

(:是do​​-nothing命令;参数被计算,然后被忽略。它是:=扩展的评估,它实际上设置了MYSQLUSER的值。)

#1


Just use:

your_var=${MYSQLUSER:-root}

The ${var:-$DEFAULT} means: If var not set or is empty, evaluate expression as $DEFAULT *.

$ {var: - $ DEFAULT}表示:如果var未设置或为空,则将表达式计算为$ DEFAULT *。


All together, I would rewrite the script to something like:

总而言之,我会将脚本重写为:

#!/bin/bash
printf "MySQL User: (root) "
read MYSQLUSER
MYSQLUSER=${MYSQLUSER:-root}
echo "mysqluser: $MYSQLUSER"

See its execution with different behaviours:

查看具有不同行为的执行情况:

$ ./a.sh 
MySQL User: (root)              #just pressed intro
mysqluser: root
$ ./a.sh 
MySQL User: (root) hello        #I wrote 'hello'
mysqluser: hello

#2


A common idiom is to use the command

常用的习惯用法是使用该命令

: ${MYSQLUSR:=root}

which assigns the value root to MYSQLUSER if it does not already have a non-null value.

如果值尚未具有非空值,则将值赋给MYSQLUSER。

(: is the do-nothing command; the arguments are evaluated, then ignored. It's the evaluation of the := expansion that actually sets the value of MYSQLUSER.)

(:是do​​-nothing命令;参数被计算,然后被忽略。它是:=扩展的评估,它实际上设置了MYSQLUSER的值。)