2010-04-05 9 views
13
#!/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 

Il problema che sto avendo è proprio qui:Come si usa un numero di argomento variabile in uno script bash?

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

Voglio semplicemente iterare su tutti gli argomenti non tra cui il primo, dovrebbe essere abbastanza facile, ma sto avendo un momento difficile capire come fare questo lavoro

risposta

15

dalla pagina man di 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. 

Così il vostro ciclo è andare a guardare qualcosa di simile:

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

Se tutti si sta cercando di fare è un ciclo su argomenti, provare qualcosa di simile:

for type in "[email protected]"; do 
    types="$types -o -name *.$type" 
done 

Per ottenere il codice di lavoro, però, provate questo:

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

questo funziona, ma non capisco perché il! è richiesto, sembra che $ {num} funzioni. Come leggeresti quella statuetta? sembra "non num", ma questo non ha senso –

+0

$ {num} è uguale a $ num. $ {! num} è la notazione per una variabile indiretta. Sembra che anche \ $$ num funzioni, anche se, secondo quello che ho letto, "La notazione $ {! Variabile} è di gran lunga superiore alla precedente" eval var1 = \ $$ var2 "" (http: // www.faqs.org/docs/abs/HTML/bash2.html) – amertune

1

se non vuoi includere il primo, il modo per farlo è usare il turno. Oppure puoi provare questo. Immaginiamo variabile s è la vostra argomenti passati.

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

Naturalmente, questo assumere non sarà di passaggio nelle stringhe che è una parola di per sé.

Problemi correlati