Bash:如何通过参数设置变量,并使用默认值 [英] Bash: How to set a variable from argument, and with a default value
问题描述
很明显,由于所有不同的变量扩展方法和程序(例如 test
和 [
和 [[
等)
It is pretty clear that with shell scripting this sort of thing can be accomplished in a huge number of ways (more than most programming languages) because of all the different variable expansion methods and programs like test
and [
and [[
, etc.
现在我正在寻找
DIR=$1 or .
意味着,我的DIR变量应包含第一个arg中或当前目录中指定的内容.
Meaning, my DIR variable should contain either what is specified in the first arg or the current directory.
此代码与 DIR = $ {1-.}
有什么区别?
我发现连字符语法令人困惑,并寻求更具可读性的语法.
I find the hyphen syntax confusing, and seek more readable syntax.
我为什么不能这样做?
DIR="$1" || '.'
我猜这意味着如果$ 1为空,则赋值仍然有效(DIR变为空),因此无效命令'."永远不会被执行."
I'm guessing this means "if $1 is empty, the assignment still works (DIR becomes empty), so the invalid command '.' never gets executed."
推荐答案
我在这里看到了几个问题.
I see several questions here.
-
我能写一些实际反映这种逻辑的东西吗"
"Can I write something that actually reflects this logic"
是的.有几种方法可以做到.这是一个:
Yes. There are a few ways you can do it. Here's one:
if [[ "$1" != "" ]]; then
DIR="$1"
else
DIR=.
fi
此代码与 DIR = $ {1-.}
有什么区别?"
语法 $ {1-.}
扩展为.
如果未设置 $ 1
,则扩展为 $ 1
如果已设置 $ 1
-即使 $ 1
设置为空字符串.
The syntax ${1-.}
expands to .
if $1
is unset, but expands like $1
if $1
is set—even if $1
is set to the empty string.
语法 $ {1:-.}
扩展为.
如果未设置 $ 1
或将其设置为空字符串.仅当 $ 1
设置为空字符串以外的其他内容时,它才会像 $ 1
那样扩展.
The syntax ${1:-.}
expands to .
if $1
is unset or is set to the empty string. It expands like $1
only if $1
is set to something other than the empty string.
为什么我不能这样做? DIR ="$ 1" ||'.'
"
"Why can't I do this? DIR="$1" || '.'
"
因为这是bash,不是perl或ruby或其他某种语言.(对不起,我的傲慢.)
Because this is bash, not perl or ruby or some other language. (Pardon my snideness.)
在bash中, ||
分隔整个命令(从技术上说,它分隔管道).它不会分隔表达式.
In bash, ||
separates entire commands (technically it separates pipelines). It doesn't separate expressions.
所以 DIR ="$ 1" ||."
的意思是执行 DIR ="$ 1"
,如果退出时返回非零退出代码,则执行'.'
".
So DIR="$1" || '.'
means "execute DIR="$1"
, and if that exits with a non-zero exit code, execute '.'
".
这篇关于Bash:如何通过参数设置变量,并使用默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!