Convert command line arguments into an array in Bash

后端 未结 7 1350
清歌不尽
清歌不尽 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:32

    Side-by-side view of how the array and $@ are practically the same.

    Code:

    #!/bin/bash
    
    echo "Dollar-1 : $1"
    echo "Dollar-2 : $2"
    echo "Dollar-3 : $3"
    echo "Dollar-AT: $@"
    echo ""
    
    myArray=( "$@" )
    
    echo "A Val 0: ${myArray[0]}"
    echo "A Val 1: ${myArray[1]}"
    echo "A Val 2: ${myArray[2]}"
    echo "A All Values: ${myArray[@]}"
    

    Input:

    ./bash-array-practice.sh 1 2 3 4
    

    Output:

    Dollar-1 : 1
    Dollar-2 : 2
    Dollar-3 : 3
    Dollar-AT: 1 2 3 4
    
    A Val 0: 1
    A Val 1: 2
    A Val 2: 3
    A All Values: 1 2 3 4
    

提交回复
热议问题