Convert command line arguments into an array in Bash

后端 未结 7 1228
清歌不尽
清歌不尽 2020-11-27 11:10

How do I convert command-line arguments into a bash script array?

I want to take this:

./something.sh arg1 arg2 arg3

and convert it

相关标签:
7条回答
  • 2020-11-27 11:54

    The importance of the double quotes is worth emphasizing. Suppose an argument contains whitespace.

    Code:

    #!/bin/bash
    printf 'arguments:%s\n' "$@"
    declare -a arrayGOOD=( "$@" )
    declare -a arrayBAAD=(  $@  )
    
    printf '\n%s:\n' arrayGOOD
    declare -p arrayGOOD
    arrayGOODlength=${#arrayGOOD[@]}
    for (( i=1; i<${arrayGOODlength}+1; i++ ));
    do
       echo "${arrayGOOD[$i-1]}"
    done
    
    printf '\n%s:\n' arrayBAAD
    declare -p arrayBAAD
    arrayBAADlength=${#arrayBAAD[@]}
    for (( i=1; i<${arrayBAADlength}+1; i++ ));
    do
       echo "${arrayBAAD[$i-1]}"
    done
    

    Output:

    > ./bash-array-practice.sh 'The dog ate the "flea" -- and ' the mouse.
    arguments:The dog ate the "flea" -- and 
    arguments:the
    arguments:mouse.
    
    arrayGOOD:
    declare -a arrayGOOD='([0]="The dog ate the \"flea\" -- and " [1]="the" [2]="mouse.")'
    The dog ate the "flea" -- and 
    the
    mouse.
    
    arrayBAAD:
    declare -a arrayBAAD='([0]="The" [1]="dog" [2]="ate" [3]="the" [4]="\"flea\"" [5]="--" [6]="and" [7]="the" [8]="mouse.")'
    The
    dog
    ate
    the
    "flea"
    --
    and
    the
    mouse.
    > 
    
    0 讨论(0)
提交回复
热议问题