简体   繁体   English

Shell脚本默认值

[英]shell scripting default value

I am trying to learn shell scripting and I am kind of confused with the idea of := or default value 我正在尝试学习Shell脚本,并且对:=或默认值的想法感到困惑

#!/bin/sh                                                                                                                             

echo "Please enter a number \c"
read input
input=$((input % 2))

if [ $input -eq 0 ]
then
    echo "The number is even"
else
    echo "The number is odd"
fi

echo "Beginning of second part"
a="BLA" 
a="Dennis"
echo $a
unset a
echo "a after unsetting"
echo $a
${a:=HI}
echo "unsetting a again"
unset a
echo $a

And I get this 我明白了

Dennis
a after unsetting

./ifstatement.sh: line 21: HI: command not found
unsetting a again

When you write 当你写

${a:=HI}

the shell splits the result of the expansion into words, and interprets the first word as a command, as it would for any command line. shell将扩展结果拆分为多个单词,并将第一个单词解释为命令,就像在任何命令行中一样。

Instead, write 相反,写

: "${a:=HI}"

: is a no-op command. :是无操作命令。 The quotes prevent the shell from trying to do globbing, which in rare circumstances could cause a slowdown or an error. 用引号引起来的shell不会尝试进行globing,这在极少数情况下可能会导致速度降低或出现错误。

There isn't a way to set a value that a variable will always "fall back" to when you un-set it. 没有一种方法可以设置一个值,当您取消设置变量时,该变量将始终“回退”到该值。 When you use the unset command, you are removing the variable (not just clearing the value associated with it) so it can't have any value, default or otherwise. 使用unset命令时,您将删除变量(而不仅仅是清除与之关联的值),因此它不能具有任何值(默认值或其他值)。

Instead, try a combination of two things. 而是尝试结合两种方法。 First, make sure the variable gets initialized. 首先,确保变量已初始化。 Second, create a function that sets the variable to the desired default value. 其次,创建一个将变量设置为所需默认值的函数。 Call this variable instead of unset . 调用此变量而不是unset With this combination, you can simulate a variable having a "default" value. 通过这种组合,您可以模拟具有“默认”值的变量。

${a:=HI} expands to HI , which your shell then tries to run as a command. ${a:=HI}扩展为HI ,然后您的shell尝试作为命令运行。 If you're just trying to set the value of a variable if it is not set, you may want to do something like [ -z "$b" ] && b=BYE 如果您只是尝试设置未设置的变量的值,则可能需要执行[ -z "$b" ] && b=BYE

不用调用未unset $a ,而是再次执行${a:=HI}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM