如何在 shell 中比较 2 个字符串?
我希望用户在命令行输入一些内容 -l 或 -e。 所以例如 $./report.sh -e 我想要一个 if 语句来分解他们做出的任何决定,所以我已经尝试过......
if [$1=="-e"]; echo "-e"; else; echo "-l"; fi
显然不起作用 谢谢
I want the user to input something at the command line either -l or -e.
so e.g. $./report.sh -e
I want an if statement to split up whatever decision they make so i have tried...
if [$1=="-e"]; echo "-e"; else; echo "-l"; fi
obviously doesn't work though
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我使用:
但是,为了解析参数,
getopts
可能会让您的生活更轻松:I use:
However, for parsing arguments,
getopts
might make your life easier:如果您希望将所有内容都写在一行上(通常这会导致阅读困难):
If you want it all on one line (usually it makes it hard to read):
方括号和方括号内的内容之间需要有空格。另外,只需使用一个
=
。您还需要一个then
。然而,
-e
特有的问题是它在echo
中具有特殊含义,因此您不太可能得到任何返回结果。如果您尝试echo -e
,您将看不到任何打印结果,而echo -d
和echo -f
则执行您所期望的操作。在其旁边放置一个空格,或将其括在括号中,或使用其他方式使其在发送到echo
时不完全是-e
。You need spaces between the square brackets and what goes inside them. Also, just use a single
=
. You also need athen
.The problem specific to
-e
however is that it has a special meaning inecho
, so you are unlikely to get anything back. If you tryecho -e
you'll see nothing print out, whileecho -d
andecho -f
do what you would expect. Put a space next to it, or enclose it in brackets, or have some other way of making it not exactly-e
when sending toecho
.如果您只想打印用户提交的参数,则只需使用
echo "$1"
即可。如果您想在用户未提交任何内容的情况下回退到默认值,可以使用echo "${1:--l}
(:-
是默认值的 Bash 语法)但是,如果您想要真正强大且灵活的参数处理,您可以查看getopt
:If you just want to print which parameter the user has submitted, you can simply use
echo "$1"
. If you want to fall back to a default value if the user hasn't submitted anything, you can useecho "${1:--l}
(:-
is the Bash syntax for default values). However, if you want really powerful and flexible argument handling, you could look intogetopt
: