所以我开始编写bash脚本。我可以做一些基本的事情,但仅此而已。
我想做一些东西,这样当我输入的时候:
./myprogram -t它将执行"echo true“。
如果我输入:
./myprogram -f它将执行"echo false“操作
提前感谢
发布于 2016-09-03 02:57:15
位置参数可以通过变量$1、$2等获得。
有许多方法可以实现条件。您可以使用if语句:
#!/bin/bash
if [ "$1" = -t ]
then
echo true
elif [ "$1" = -f ]
then
echo false
ficase语句:
#!/bin/bash
case "$1" in
-t) echo true ;;
-f) echo false ;;
esac或者是短路:
#!/bin/bash
[ "$1" = -t ] && echo true
[ "$1" = -f ] && echo false对于更复杂的情况,可以考虑使用getopt或getopts库。
发布于 2016-09-03 02:57:39
你所说的“选项”这个词在编程中通常被称为参数。您应该阅读更多关于如何通过读取http://tldp.org/LDP/abs/html/othertypesv.html中的所有内容来处理bash中的参数的信息。为了直接回答您的问题,脚本可能如下所示:
#!/bin/bash
if [[ $# -eq 0 ]]; then
echo 'No Arguments'
exit 0
fi
if [ $1 = "-f" ]; then
echo false
elif [ $1 = "-t" ]; then
echo true
fihttps://stackoverflow.com/questions/39298939
复制相似问题