programing

셸에서 배열의 길이를 찾는 방법은 무엇입니까?

linuxpc 2023. 4. 26. 23:02
반응형

셸에서 배열의 길이를 찾는 방법은 무엇입니까?

셸에서 배열의 길이를 찾으려면 어떻게 해야 합니까?

예:

arr=(1 2 3 4 5)

그리고 이 경우에는 5의 길이로 하고 싶습니다.

$ a=(1 2 3 4)
$ echo ${#a[@]}
4

Bash 매뉴얼에서:

${#parameter}

확장된 매개 변수 값의 문자 길이가 대체됩니다.파라미터가 " 또는 "@"인 경우 대체되는 값은 위치 파라미터의 수가 됩니다. 매개 변수가 " 또는 "@"에 의해 구독된 배열 이름인 경우 대체된 값은 배열의 요소 수입니다.매개 변수가 음수로 첨자된 인덱스 배열 이름인 경우, 해당 숫자는 매개 변수의 최대 인덱스보다 큰 하나에 상대적인 것으로 해석되므로 배열 끝에서 음수 인덱스가 카운트되고 -1의 인덱스가 마지막 요소를 참조합니다.

문자열, 배열 및 연관 배열의 길이

string="0123456789"                   # create a string of 10 characters
array=(0 1 2 3 4 5 6 7 8 9)           # create an indexed array of 10 elements
declare -A hash
hash=([one]=1 [two]=2 [three]=3)      # create an associative array of 3 elements
echo "string length is: ${#string}"   # length of string
echo "array length is: ${#array[@]}"  # length of array using @ as the index
echo "array length is: ${#array[*]}"  # length of array using * as the index
echo "hash length is: ${#hash[@]}"    # length of array using @ as the index
echo "hash length is: ${#hash[*]}"    # length of array using * as the index

출력:

string length is: 10
array length is: 10
array length is: 10
hash length is: 3
hash length is: 3

취급$@인수 배열:

set arg1 arg2 "arg 3"
args_copy=("$@")
echo "number of args is: $#"
echo "number of args is: ${#@}"
echo "args_copy length is: ${#args_copy[@]}"

출력:

number of args is: 3
number of args is: 3
args_copy length is: 3

bash로 가정:

~> declare -a foo
~> foo[0]="foo"
~> foo[1]="bar"
~> foo[2]="baz"
~> echo ${#foo[*]}
3

그렇게,${#ARRAY[*]}배열 길이로 확장됩니다.ARRAY.

tcsh 또는 csh 단위:

~> set a = ( 1 2 3 4 5 )
~> echo $#a
5

물고기 껍질에서 배열의 길이는 다음과 같이 확인할 수 있습니다.

$ set a 1 2 3 4
$ count $a
4

이것은 나에게 잘 맞습니다.

arglen=$#
argparam=$*
if [ $arglen -eq '3' ];
then
    echo Valid Number of arguments
    echo "Arguments are $*"
else
    echo only four arguments are allowed
fi

배열의 길이를 변수에 추가하는 방법을 찾는 사용자:

foo="${#ARRAY[*]}"

언급URL : https://stackoverflow.com/questions/1886374/how-to-find-the-length-of-an-array-in-shell

반응형