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

de90aj5v  于 2023-03-13  发布在  Shell
关注(0)|答案(4)|浏览(171)
#!/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

我只想迭代所有参数,不包括第一个,应该很容易,但是我很难弄清楚如何实现它

wz3gfoph

wz3gfoph1#

从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
zsbz8rwp

zsbz8rwp2#

如果你要做的只是循环遍历参数,那么试试下面的代码:

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
lfapxunr

lfapxunr3#

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

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

当然,这是假设您传入的字符串本身不是一个单词。

zengzsys

zengzsys4#

下面是一个非破坏性版本,它允许在启用errexit时访问第一个参数:

#!/usr/bin/env bash
set -o nounset -o pipefail -o errexit

Test () {
    local INDEX=0
    while [ $INDEX -lt $# ]
    do
        INDEX=$(( INDEX+1 ))
        echo "->${!INDEX}<-"
    done
}

Test a b c 1 2 3

输出:

->a<-
->b<-
->c<-
->1<-
->2<-
->3<-

这种方法不使用shift,允许参数重用,其他答案使用(( INDEX++ ))来推进索引,但是当INDEX初始设置为0时,(( INDEX++ ))递增INDEX,但是计算结果为0,Bash认为这是错误的。

相关问题