我不知道是否可能,但我想编写shell脚本,其作用类似于带有选项的常规可执行文件.作为一个非常简单的示例,请考虑配置为可执行的shell脚本foo.sh:
./foo.sh
./foo.sh -o
Run Code Online (Sandbox Code Playgroud)
而代码的foo.sh作用就像
#!/bin/sh
if ## option -o is turned on
## do something
else
## do something different
endif
Run Code Online (Sandbox Code Playgroud)
有可能,怎么做?谢谢.
Suk*_*uku 21
$ cat stack.sh
#!/bin/sh
if [[ $1 = "-o" ]]; then
echo "Option -o turned on"
else
echo "You did not use option -o"
fi
$ bash stack.sh -o
Option -o turned on
$ bash stack.sh
You did not use option -o
Run Code Online (Sandbox Code Playgroud)
供参考:
$1 = First positional parameter
$2 = Second positional parameter
.. = ..
$n = n th positional parameter
Run Code Online (Sandbox Code Playgroud)
有关更多整洁/灵活的选项,请阅读此其他线程:在bash shell脚本中使用getopts以获取长和短命令行选项
小智 12
这是在一个脚本中如何做到这一点的方式:
#!/usr/bin/sh
#
# Examlple of using options in scripts
#
if [ $# -eq 0 ]
then
echo "Missing options!"
echo "(run $0 -h for help)"
echo ""
exit 0
fi
ECHO="false"
while getopts "he" OPTION; do
case $OPTION in
e)
ECHO="true"
;;
h)
echo "Usage:"
echo "args.sh -h "
echo "args.sh -e "
echo ""
echo " -e to execute echo \"hello world\""
echo " -h help (this output)"
exit 0
;;
esac
done
if [ $ECHO = "true" ]
then
echo "Hello world";
fi
Run Code Online (Sandbox Code Playgroud)
点击这里获取资源