繁体   English   中英

如何在bash脚本中使用变量参数号?

[英]How do I use a variable argument number in a bash script?

#!/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 *."$1

#loop through additional filetypes and append
num=1
while [ $num -lt $# ]
do
  (( num++ ))
  types=$types' -o -name *.'$$num
done

echo "TYPES="$types

find . -name '*.'$1 | xargs du -ch *.$1 | grep total

我遇到的问题就在这里:

 #loop through additional filetypes and append
    num=1
    while [ $num -lt $# ]
    do
      (( num++ ))
      types=$types' -o -name *.'>>$$num<<
    done

我只是想迭代所有的参数,不包括第一个,应该很容易,但我很难搞清楚如何使这项工作

来自bash手册页:

  shift [n]
          The  positional  parameters  from n+1 ... are renamed to $1 ....
          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.

所以你的循环看起来像这样:

#loop through additional filetypes and append
while [ $# -gt 0 ]
do
  types=$types' -o -name *.'$1
  shift
done

如果您要做的就是遍历参数,请尝试以下方法:

for type in "$@"; do
    types="$types -o -name *.$type"
done

要使代码正常工作,请尝试以下方法:

#loop through additional filetypes and append
num=1
while [ $num -le $# ]
do
    (( num++ ))
    types=$types' -o -name *.'${!num}
done

如果你不想包含第一个,那么这样做的方法就是使用shift。 或者你可以试试这个。 想象变量s是你传入的参数。

$ s="one two three"
$ echo ${s#* }
two three

当然,这假设你不会传递一个单词的字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM