[英]Options on bash script (completely new to this)
So I'm beginning making bash scripts. 所以我开始制作bash脚本。 I can do basic stuff, but that's it.
我可以做一些基本的事情,仅此而已。
I want to make something so when I type in: 我想输入以下内容:
./myprogram -t
It will do "echo true" 它将做“回声真实”
And if I type in: 如果我输入:
./myprogram -f
It will do "echo false" 它将做“回声错误”
Thanks in advance 提前致谢
The positional parameters are available through the variables $1
$2
etc. 位置参数可通过变量
$1
$2
等获得。
There are many ways to implement the contition. 有许多方法可以实现竞争。 You could use an if statement:
您可以使用if语句:
#!/bin/bash
if [ "$1" = -t ]
then
echo true
elif [ "$1" = -f ]
then
echo false
fi
A case statement: 案例说明:
#!/bin/bash
case "$1" in
-t) echo true ;;
-f) echo false ;;
esac
Or a short-circuit: 或短路:
#!/bin/bash
[ "$1" = -t ] && echo true
[ "$1" = -f ] && echo false
For more complex cases consider using the getopt
or the getopts
libraries. 对于更复杂的情况,请考虑使用
getopt
或getopts
库。
The word for what you are calling an "option" is typically referred to as an argument in programming. 所谓的“选项”一词在编程中通常称为自变量。 You should read more about how to handle arguments in bash by reading everything at http://tldp.org/LDP/abs/html/othertypesv.html .
您应该通过阅读http://tldp.org/LDP/abs/html/othertypesv.html上的所有内容,详细了解如何在bash中处理参数。 To answer your direct question the script might look like this:
要回答您的直接问题,脚本可能如下所示:
#!/bin/bash
if [[ $# -eq 0 ]]; then
echo 'No Arguments'
exit 0
fi
if [ $1 = "-f" ]; then
echo false
elif [ $1 = "-t" ]; then
echo true
fi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.