如何在 bash 脚本中使用可变参数编号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2581696/
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
How do I use a variable argument number in a bash script?
提问by Corbin Tarrant
#!/bin/bash
# Script to output the total size of requested filetype recursively
# Error out if no file types were provided
if [ $# -lt 1 ]
then
echo "Syntax Error, Please provide at least one type, ex: sizeofTypes {filetype1} {filetype2}"
exit 0
fi
#set first filetype
types="-name *."
#loop through additional filetypes and append
num=1
while [ $num -lt $# ]
do
(( num++ ))
types=$types' -o -name *.'$$num
done
echo "TYPES="$types
find . -name '*.' | xargs du -ch *. | grep total
The problem I'm having is right here:
我遇到的问题就在这里:
#loop through additional filetypes and append
num=1
while [ $num -lt $# ]
do
(( num++ ))
types=$types' -o -name *.'>>$$num<<
done
I simply want to iterate over all the arguments not including the first one, should be easy enough, but I'm having a difficult time figuring out how to make this work
我只是想迭代所有参数,不包括第一个,应该很容易,但我很难弄清楚如何使这项工作
回答by Zac Thompson
from the bash man page:
从 bash 手册页:
shift [n]
The positional parameters from n+1 ... are renamed to ....
Parameters represented by the numbers $# down to $#-n+1 are
unset. n must be a non-negative number less than or equal to
$#. If n is 0, no parameters are changed. If n is not given,
it is assumed to be 1. If n is greater than $#, the positional
parameters are not changed. The return status is greater than
zero if n is greater than $# or less than zero; otherwise 0.
So your loop is going to look something like this:
所以你的循环看起来像这样:
#loop through additional filetypes and append
while [ $# -gt 0 ]
do
types=$types' -o -name *.'
shift
done
回答by amertune
If all you're trying to do is loop over the arguments, try something like this:
如果您要做的只是遍历参数,请尝试以下操作:
for type in "$@"; do
types="$types -o -name *.$type"
done
To get your code working though, try this:
为了让您的代码正常工作,请尝试以下操作:
#loop through additional filetypes and append
num=1
while [ $num -le $# ]
do
(( num++ ))
types=$types' -o -name *.'${!num}
done
回答by ghostdog74
if you don't want to include the first one, the way to do that is to use shift. Or you can try this. imagine variable s
is your arguments passed in.
如果您不想包含第一个,那么这样做的方法是使用 shift。或者你可以试试这个。想象变量s
是你传入的参数。
$ s="one two three"
$ echo ${s#* }
two three
Of course, this assume you won't be passing in strings that is one word by itself.
当然,这假设您不会传入一个单独的单词的字符串。