【问题标题】:How do I use a variable argument number in a bash script?如何在 bash 脚本中使用可变参数编号?
【发布时间】:2010-04-05 23:03:33
【问题描述】:
#!/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 shell


    【解决方案1】:

    来自 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
    

    【讨论】:

      【解决方案2】:

      如果您只想循环遍历参数,请尝试以下操作:

      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
      

      【讨论】:

      • 这行得通,但我不明白为什么!是必需的,似乎 ${num} 应该可以工作。你会怎么读那句话?看起来像“not num”,但这没有意义
      • ${num} 与 $num 相同。 ${!num} 是间接变量的表示法。看起来 \$$num 也可以工作,尽管根据我所读到的内容,“${!variable} 表示法大大优于旧的 'eval var1=\$$var2'”(faqs.org/docs/abs/HTML/bash2.html
      【解决方案3】:

      如果您不想包含第一个,则可以使用 shift。或者你可以试试这个。想象变量s 是你传入的参数。

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

      当然,这假设您不会传入单独为一个单词的字符串。

      【讨论】:

        猜你喜欢
        • 2013-04-16
        • 1970-01-01
        • 2016-08-10
        • 2010-12-31
        • 2019-02-08
        • 2012-03-09
        • 2012-06-05
        相关资源
        最近更新 更多