Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
是否可以使用短路为 shell 脚本设置变量默认值?
脚本调用 1:my_script.sh "apple" "carrot"
my_script.sh "apple" "carrot"
脚本调用 2:my_script.sh "apple"
my_script.sh "apple"
my_script.sh:
#!/bin/bash fruit=$1 vegetable=$2 || "green bean" # Do something with fruits and vegetables
当我这样做时,似乎从未使用过默认值。
您可以使用以下语法:
a=${1:-default}
您是否指出脚本应该使用特定的外壳?我总是默认这样使用bash:
bash
#!/bin/bash
这里很好地解释了这个概念。
编辑:好的,我现在更好地理解了这个问题。如果未传递变量,原始发布者希望设置默认值。很好的解释在这里设置默认变量。试试这个脚本:
#!/bin/bash fruit=${1-apple} vegetable=${2-green bean} echo $fruit; echo $vegetable;