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

后端 未结 3 1790
渐次进展
渐次进展 2020-12-31 06:52
#!/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 Err         


        
相关标签:
3条回答
  • 2020-12-31 07:11

    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.

    $ 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.

    0 讨论(0)
  • 2020-12-31 07:16

    from the bash man page:

      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.
    

    So your loop is going to look something like this:

    #loop through additional filetypes and append
    while [ $# -gt 0 ]
    do
      types=$types' -o -name *.'$1
      shift
    done
    
    0 讨论(0)
  • 2020-12-31 07:31

    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
    
    0 讨论(0)
提交回复
热议问题