Linux Check that there are at least two arguments given in a bash script
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7989486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check that there are at least two arguments given in a bash script
提问by BillPull
I am trying to write a script that mimics cp where there is a source and destination input. how can I count the number of arguments given on the command line
I am trying to write a script that mimics cp where there is a source and destination input. how can I count the number of arguments given on the command line
for example
for example
./myscript src dest
./myscript src dest
check that at least 2 things were given.
check that at least 2 things were given.
采纳答案by Laurence Gonsalves
Use the $#special variable. Its value is the number of arguments. So if you have a script that contains only:
Use the $#special variable. Its value is the number of arguments. So if you have a script that contains only:
echo $#
and execute it like this:
and execute it like this:
thatscript foo bar baz quux
It'll print 4.
It'll print 4.
In your case you may want to do something like:
In your case you may want to do something like:
if [ $# -lt 2 ]; then
# TODO: print usage
exit 1
fi
回答by Andrew
Going by the requirement from the question that the arguments should contain "at least 2 things", I think it might be more accurate to check:
Going by the requirement from the question that the arguments should contain "at least 2 things", I think it might be more accurate to check:
if (( $# < 2 )); then
# TODO: print usage
exit 1
fi
Using arithmetic expansion(())will prevent this from hitting exit 1for any value not equal to 2.
Using arithmetic expansion(())will prevent this from hitting exit 1for any value not equal to 2.
If you use if [ $# -ne 2 ];it will trigger the conditional for any number of arguments other than 2.
If you use if [ $# -ne 2 ];it will trigger the conditional for any number of arguments other than 2.

