Bash中的命令行参数 [英] Command line arguments in Bash
本文介绍了Bash中的命令行参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想编写一个使用不同参数的bash脚本.应该像普通的Linux控制台程序一样使用它:
I want to write a bash script which takes different arguments. It should be used like normal linux console programs:
my_bash_script -p 2 -l 5 -t 20
因此,值2应该保存在称为pages的变量中,参数l应该保存在称为length的变量中,而值20应该保存在可变时间中.
So the value 2 should be saved in a variable called pages and the parameter l should be saved in a variable called length and the value 20 should be saved in a variable time.
做到这一点的最佳方法是什么?
What is the best way to do this?
推荐答案
使用内置的getopts
:
这是一个教程
Use the getopts
builtin:
here's a tutorial
pages= length= time=
while getopts p:l:t: opt; do
case $opt in
p)
pages=$OPTARG
;;
l)
length=$OPTARG
;;
t)
time=$OPTARG
;;
esac
done
shift $((OPTIND - 1))
shift $((OPTIND - 1))
转换命令行参数,以便您可以访问脚本的可能参数,即$1, $2, ...
shift $((OPTIND - 1))
shifts the command line parameters so that you can access possible arguments to your script, i.e. $1, $2, ...
这篇关于Bash中的命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文