유닉스 쉘 스크립팅에서 배열을 어떻게 생성합니까?
답변
다음 코드는 셸에서 문자열 배열을 만들고 인쇄합니다.
#!/bin/bash
array=("A" "B" "ElementC" "ElementE")
for element in "${array[@]}"
do
echo "$element"
done
echo
echo "Number of elements: ${#array[@]}"
echo
echo "${array[@]}"
결과:
A
B
ElementC
ElementE
Number of elements: 4
A B ElementC ElementE
답변
bash에서는 다음과 같은 배열을 만듭니다.
arr=(one two three)
요소를 호출하려면
$ echo "${arr[0]}"
one
$ echo "${arr[2]}"
three
사용자 입력을 요청하려면 읽기를 사용할 수 있습니다.
read -p "Enter your choice: " choice
답변
Bourne 쉘은 배열을 지원하지 않습니다. 그러나 문제를 처리하는 방법에는 두 가지가 있습니다.
위치 쉘 매개 변수 $ 1, $ 2 등을 사용하십시오.
$ set one two three
$ echo $*
one two three
$ echo $#
3
$ echo $2
two
변수 평가 사용 :
$ n=1 ; eval a$n="one"
$ n=2 ; eval a$n="two"
$ n=3 ; eval a$n="three"
$ n=2
$ eval echo \$a$n
two
답변
#!/bin/bash
# define a array, space to separate every item
foo=(foo1 foo2)
# access
echo "${foo[1]}"
# add or changes
foo[0]=bar
foo[2]=cat
foo[1000]=also_OK
ABS “Advanced Bash-Scripting Guide”를 읽을 수 있습니다.
답변
Bourne 쉘과 C 쉘에는 IIRC라는 배열이 없습니다.
다른 사람들이 말한 것 외에도 Bash에서 다음과 같이 배열의 요소 수를 얻을 수 있습니다.
elements=${#arrayname[@]}
슬라이스 스타일 작업을 수행합니다.
arrayname=(apple banana cherry)
echo ${arrayname[@]:1} # yields "banana cherry"
echo ${arrayname[@]: -1} # yields "cherry"
echo ${arrayname[${#arrayname[@]}-1]} # yields "cherry"
echo ${arrayname[@]:0:2} # yields "apple banana"
echo ${arrayname[@]:1:1} # yields "banana"
답변
이 시도 :
echo "Find the Largest Number and Smallest Number of a given number"
echo "---------------------------------------------------------------------------------"
echo "Enter the number"
read n
i=0
while [ $n -gt 0 ] #For Seperating digits and Stored into array "x"
do
x[$i]=`expr $n % 10`
n=`expr $n / 10`
i=`expr $i + 1`
done
echo "Array values ${x[@]}" # For displaying array elements
len=${#x[*]} # it returns the array length
for (( i=0; i<len; i++ )) # For Sorting array elements using Bubble sort
do
for (( j=i+1; j<len; j++ ))
do
if [ `echo "${x[$i]} > ${x[$j]}"|bc` ]
then
t=${x[$i]}
t=${x[$i]}
x[$i]=${x[$j]}
x[$j]=$t
fi
done
done
echo "Array values ${x[*]}" # Displaying of Sorted Array
for (( i=len-1; i>=0; i-- )) # Form largest number
do
a=`echo $a \* 10 + ${x[$i]}|bc`
done
echo "Largest Number is : $a"
l=$a #Largest number
s=0
while [ $a -gt 0 ] # Reversing of number, We get Smallest number
do
r=`expr $a % 10`
s=`echo "$s * 10 + $r"|bc`
a=`expr $a / 10`
done
echo "Smallest Number is : $s" #Smallest Number
echo "Difference between Largest number and Smallest number"
echo "=========================================="
Diff=`expr $l - $s`
echo "Result is : $Diff"
echo "If you try it, We can get it"
답변
귀하의 질문은 “unix shell scripting”에 대해 묻지 만 태그는 bash
. 두 가지 대답이 있습니다.
쉘에 대한 POSIX 사양에는 원래 Bourne 쉘이 지원하지 않았기 때문에 어레이에 대해 말할 것이 없습니다. 오늘날에도 FreeBSD, Ubuntu Linux 및 기타 많은 시스템에서는 /bin/sh
어레이를 지원하지 않습니다. 따라서 스크립트가 다른 Bourne 호환 셸에서 작동하도록하려면 사용하지 않아야합니다. 또는 특정 셸을 가정하는 경우 shebang 줄에 전체 이름을 입력해야합니다 (예 : #!/usr/bin/env bash
.
당신이 사용하는 경우 bash는 또는 zsh을 , 또는의 현대 버전 KSH를 ,이 같은 배열을 만들 수 있습니다 :
myArray=(first "second element" 3rd)
이와 같은 액세스 요소
$ echo "${myArray[1]}"
second element
을 통해 모든 요소를 얻을 수 있습니다 "${myArray[@]}"
. 슬라이스 표기법 $ {array [@] : start : length} 를 사용하여 참조되는 배열의 부분을 제한 할 수 있습니다 (예 : "${myArray[@]:1}"
첫 번째 요소를 제외).
배열의 길이는 ${#myArray[@]}
입니다. 를 사용하여 기존 배열의 모든 인덱스를 포함하는 새 배열을 가져올 수 있습니다 "${!myArray[@]}"
.
ksh93 이전 버전의 ksh에도 배열이 있었지만 괄호 기반 표기법은 없었으며 슬라이싱도 지원하지 않았습니다. 하지만 다음과 같은 배열을 만들 수 있습니다.
set -A myArray -- first "second element" 3rd
