Bash quoted array expansion

前端 未结 6 946
借酒劲吻你
借酒劲吻你 2021-01-31 02:57

WHen I write a bash program I typically construct calls like follows:

declare -a mycmd=( command.ext \"arg1 with space\" arg2 thing etc )

\"${mycmd[@]}\" || ech         


        
6条回答
  •  闹比i
    闹比i (楼主)
    2021-01-31 03:24

    Another approach

    # echo_array.sh
    
    contains_space(){ [[ "$1" =~ " " ]]; return $?; }
    maybe_quote_one(){ contains_space "$1"  &&  echo \'"$1"\'  ||  echo "$1"; }
    maybe_quote(){ while test "$1"; do maybe_quote_one "$1"; shift; done; }
    
    arridx(){ echo '${'$1'['$2']}'; }
    arrindir(){ echo $(eval echo `arridx $1 $2`); }
    arrsize(){ echo `eval echo '${'#$1'[@]}'`; }
    
    echo_array()
    { 
        echo -n "$1=( "
        local i=0
        for (( i=0; i < `arrsize a`; i++ )); do
            echo -n $(maybe_quote "$(arrindir $1 $i)") ''
        done
        echo ")"
    }
    

    Usage:

    source echo_array.sh
    a=( foo bar baz "It was hard" curious '67 - 00' 44 'my index is 7th' )
    echo_array a
    # a=( foo bar baz 'It was hard' curious '67 - 00' 44 'my index is 7th'  )
    arrindir a 7
    # my index is 7th
    arrindir a 0
    # foo
    arrsize a
    # 8
    

    $ bash --version

    GNU bash, version 4.3.48(1)-release (x86_64-pc-linux-gnu)
    Copyright (C) 2013 Free Software Foundation, Inc.
    

提交回复
热议问题