15개 문자열을 반복하는 스크립트를 작성하고 싶습니다(배열 가능할까요?) 가능합니까?
다음과 같은 것:
for databaseName in listOfNames then # Do something end
질문자 :Mo.
15개 문자열을 반복하는 스크립트를 작성하고 싶습니다(배열 가능할까요?) 가능합니까?
다음과 같은 것:
for databaseName in listOfNames then # Do something end
다음과 같이 사용할 수 있습니다.
## declare an array variable declare -a arr=("element1" "element2" "element3") ## now loop through the above array for i in "${arr[@]}" do echo "$i" # or do whatever with individual element of the array done # You can access them using echo "${arr[0]}", "${arr[1]}" also
여러 줄 배열 선언에서도 작동합니다.
declare -a arr=("element1" "element2" "element3" "element4" )
물론 가능합니다.
for databaseName in abcdef; do # do something like: echo $databaseName done
자세한 내용은 Bash 루프 for, while 및 until 을 참조하십시오.
그 답변 중 어느 것도 카운터를 포함하지 않습니다 ...
#!/bin/bash ## declare an array variable declare -a array=("one" "two" "three") # get length of an array arraylength=${#array[@]} # use for loop to read all values and indexes for (( i=0; i<${arraylength}; i++ )); do echo "index: $i, value: ${array[$i]}" done
산출:
index: 0, value: one index: 1, value: two index: 2, value: three
예
for Item in Item1 Item2 Item3 Item4 ; do echo $Item done
산출:
Item1 Item2 Item3 Item4
공간을 보존하기 위해; 작은따옴표 또는 큰따옴표 목록 항목 및 큰따옴표 목록 확장.
for Item in 'Item 1' 'Item 2' 'Item 3' 'Item 4' ; do echo "$Item" done
산출:
Item 1 Item 2 Item 3 Item 4
여러 줄에 걸쳐 목록을 만들려면
for Item in Item1 \ Item2 \ Item3 \ Item4 do echo $Item done
산출:
Item1 Item2 Item3 Item4
List=( Item1 Item2 Item3 )
또는
List=( Item1 Item2 Item3 )
목록 변수를 표시합니다.
echo ${List[*]}
산출:
Item1 Item2 Item3
목록을 반복합니다.
for Item in ${List[*]} do echo $Item done
산출:
Item1 Item2 Item3
목록을 탐색하는 함수를 만듭니다.
Loop(){ for item in ${*} ; do echo ${item} done } Loop ${List[*]}
선언 키워드(명령어)를 사용하여 기술적으로 배열이라고 하는 목록을 만듭니다.
declare -a List=( "element 1" "element 2" "element 3" ) for entry in "${List[@]}" do echo "$entry" done
산출:
element 1 element 2 element 3
연관 배열 만들기. 사전:
declare -A continent continent[Vietnam]=Asia continent[France]=Europe continent[Argentina]=America for item in "${!continent[@]}"; do printf "$item is in ${continent[$item]} \n" done
산출:
Argentina is in America Vietnam is in Asia France is in Europe
CSV 변수 또는 파일을 목록에 추가합니다 .
내부 필드 구분 기호를 공백에서 원하는 대로 변경합니다.
아래 예에서는 쉼표로 변경되었습니다.
List="Item 1,Item 2,Item 3" Backup_of_internal_field_separator=$IFS IFS=, for item in $List; do echo $item done IFS=$Backup_of_internal_field_separator
산출:
Item 1 Item 2 Item 3
번호를 매겨야 하는 경우:
`
이것을 백 틱이라고 합니다. 명령을 백 틱 안에 넣으십시오.
`command`
표준 미국 영어 키보드에서 키보드의 숫자 1 옆 및/또는 탭 키 위에 있습니다.
List=() Start_count=0 Step_count=0.1 Stop_count=1 for Item in `seq $Start_count $Step_count $Stop_count` do List+=(Item_$Item) done for Item in ${List[*]} do echo $Item done
출력은 다음과 같습니다.
Item_0.0 Item_0.1 Item_0.2 Item_0.3 Item_0.4 Item_0.5 Item_0.6 Item_0.7 Item_0.8 Item_0.9 Item_1.0
bash 동작에 더 익숙해지기:
파일에 목록 만들기
cat <<EOF> List_entries.txt Item1 Item 2 'Item 3' "Item 4" Item 7 : * "Item 6 : * " "Item 6 : *" Item 8 : $PWD 'Item 8 : $PWD' "Item 9 : $PWD" EOF
목록 파일을 목록으로 읽고 표시
List=$(cat List_entries.txt) echo $List echo '$List' echo "$List" echo ${List[*]} echo '${List[*]}' echo "${List[*]}" echo ${List[@]} echo '${List[@]}' echo "${List[@]}"
4ndrew의 답변과 같은 정신으로 :
listOfNames="RA RB RC RD" # To allow for other whitespace in the string: # 1. add double quotes around the list variable, or # 2. see the IFS note (under 'Side Notes') for databaseName in "$listOfNames" # <-- Note: Added "" quotes. do echo "$databaseName" # (ie do action / processing of $databaseName here...) done # Outputs # RA # RB # RC # RD
B. 이름에 공백 없음:
listOfNames="RA RB RC RD" for databaseName in $listOfNames # Note: No quotes do echo "$databaseName" # (ie do action / processing of $databaseName here...) done # Outputs # RA # RB # R # C # RD
노트
listOfNames="RA RB RC RD"
를 사용하면 동일한 출력이 나타납니다.데이터를 가져오는 다른 방법은 다음과 같습니다.
표준 입력에서 읽기
# line delimited (each databaseName is stored on a line) while read databaseName do echo "$databaseName" # ie do action / processing of $databaseName here... done # <<< or_another_input_method_here
IFS='\n'
또는 MacOS IFS='\r'
).#!/bin/bash
를 포함하면 실행 환경을 나타냅니다.기타 소스( 읽는 동안 루프 )
${arrayName[@]}
구문을 사용할 수 있습니다.
#!/bin/bash # declare an array called files, that contains 3 values files=( "/etc/passwd" "/etc/group" "/etc/hosts" ) for i in "${files[@]}" do echo "$i" done
아무도 이것을 아직 게시하지 않았다는 사실에 놀랐습니다. 배열을 반복하는 동안 요소의 인덱스가 필요한 경우 다음을 수행할 수 있습니다.
arr=(foo bar baz) for i in ${!arr[@]} do echo $i "${arr[i]}" done
산출:
0 foo 1 bar 2 baz
나는 이것이 "전통적인" for-loop 스타일( for (( i=0; i<${#arr[@]}; i++ ))
)보다 훨씬 더 우아하다는 것을 알았습니다.
( ${!arr[@]}
과 $i
는 단지 숫자이기 때문에 인용할 필요가 없습니다. 어떤 사람들은 어쨌든 인용을 제안하지만 그것은 단지 개인적인 취향입니다.)
이것은 또한 읽기 쉽습니다:
FilePath=( "/tmp/path1/" #FilePath[0] "/tmp/path2/" #FilePath[1] ) #Loop for Path in "${FilePath[@]}" do echo "$Path" done
listOfNames="db_one db_two db_three" for databaseName in $listOfNames do echo $databaseName done
아니면 그냥
for databaseName in db_one db_two db_three do echo $databaseName done
anubhava 의 정답 외에: 루프의 기본 구문이 다음과 같은 경우:
for var in "${arr[@]}" ;do ...$var... ;done
bash 에는 특별한 경우가 있습니다.
스크립트나 함수를 실행할 때 명령줄에 전달된 인수 $@
$1
, $2
, $3
등으로 액세스할 수 있습니다.
이것은 (테스트를 위해) 다음으로 채워질 수 있습니다.
set -- arg1 arg2 arg3 ...
이 배열에 대한 루프 는 다음과 같이 간단하게 작성할 수 있습니다.
for item ;do echo "This is item: $item." done
예약 된 작업을 참고 in
표시되지 않으며 배열 이름도!
견본:
set -- arg1 arg2 arg3 ... for item ;do echo "This is item: $item." done This is item: arg1. This is item: arg2. This is item: arg3. This is item: ....
이것은 다음과 동일합니다.
for item in "$@";do echo "This is item: $item." done
#!/bin/bash for item ;do printf "Doing something with '%s'.\n" "$item" done
이것을 스크립트 myscript.sh
, chmod +x myscript.sh
에 저장한 다음
./myscript.sh arg1 arg2 arg3 ... Doing something with 'arg1'. Doing something with 'arg2'. Doing something with 'arg3'. Doing something with '...'.
myfunc() { for item;do cat <<<"Working about '$item'."; done ; }
그 다음에
myfunc item1 tiem2 time3 Working about 'item1'. Working about 'tiem2'. Working about 'time3'.
간단한 방법:
arr=("sharlock" "bomkesh" "feluda" ) ##declare array len=${#arr[*]} # it returns the array length #iterate with while loop i=0 while [ $i -lt $len ] do echo ${arr[$i]} i=$((i+1)) done #iterate with for loop for i in $arr do echo $i done #iterate with splice echo ${arr[@]:0:3}
선언 배열은 Korn 셸에서 작동하지 않습니다. Korn 쉘의 경우 아래 예를 사용하십시오.
promote_sla_chk_lst="cdi xlob" set -A promote_arry $promote_sla_chk_lst for i in ${promote_arry[*]}; do echo $i done
이 시도. 작동 중이며 테스트 중입니다.
for k in "${array[@]}" do echo $k done # For accessing with the echo command: echo ${array[0]}, ${array[1]}
이것은 user2533809님의 답변과 비슷하지만 각각의 파일은 별도의 명령어로 실행될 것입니다.
#!/bin/bash names="RA RB RC RD" while read -r line; do echo line: "$line" done <<< "$names"
Korn 쉘을 사용하는 경우 " set -A databaseName "이 있고, 그렇지 않으면 " 선언 -a databaseName "이 있습니다.
모든 쉘에서 작동하는 스크립트를 작성하려면,
set -A databaseName=("db1" "db2" ....) || declare -a databaseName=("db1" "db2" ....) # now loop for dbname in "${arr[@]}" do echo "$dbname" # or whatever done
모든 쉘에서 작동해야 합니다.
내가 이것을 위해 정말로 필요했던 것은 다음과 같았습니다.
for i in $(the_array); do something; done
예를 들어:
for i in $(ps -aux | grep vlc | awk '{ print $2 }'); do kill -9 $i; done
(이름에 vlc가 있는 모든 프로세스를 종료합니다)
모든 Bash 스크립트/세션의 가능한 첫 번째 줄:
say() { for line in "${@}" ; do printf "%s\n" "${line}" ; done ; }
사용 예:
$ aa=( 7 -4 -e ) ; say "${aa[@]}" 7 -4 -e
고려할 수 있습니다: echo
는 -e
여기서 옵션으로 해석합니다.
단일 라인 루핑,
declare -a listOfNames=('db_a' 'db_b' 'db_c') for databaseName in ${listOfNames[@]}; do echo $databaseName; done;
당신은 다음과 같은 출력을 얻을 것이다,
db_a db_b db_c
git pull
업데이트를 위해 내 프로젝트 배열을 반복합니다.
#!/bin/sh projects=" web ios android " for project in $projects do cd $HOME/develop/$project && git pull end
배열을 반복하는 방법은 줄 바꿈 문자의 존재 여부에 따라 다릅니다. 배열 요소를 구분하는 줄 바꿈 문자를 사용하면 배열을 "$array"
, 그렇지 않으면 "${array[@]}"
합니다. 다음 스크립트를 사용하면 명확해집니다.
#!/bin/bash mkdir temp mkdir temp/aaa mkdir temp/bbb mkdir temp/ccc array=$(ls temp) array1=(aaa bbb ccc) array2=$(echo -e "aaa\nbbb\nccc") echo '$array' echo "$array" echo for dirname in "$array"; do echo "$dirname" done echo for dirname in "${array[@]}"; do echo "$dirname" done echo echo '$array1' echo "$array1" echo for dirname in "$array1"; do echo "$dirname" done echo for dirname in "${array1[@]}"; do echo "$dirname" done echo echo '$array2' echo "$array2" echo for dirname in "$array2"; do echo "$dirname" done echo for dirname in "${array2[@]}"; do echo "$dirname" done rmdir temp/aaa rmdir temp/bbb rmdir temp/ccc rmdir temp
출처 : http:www.stackoverflow.com/questions/8880603/loop-through-an-array-of-strings-in-bash
상속보다 구성을 선호합니까? (0) | 2022.01.02 |
---|---|
TypeScript는 무엇이며 JavaScript 대신 사용하는 이유는 무엇입니까? [닫은] (0) | 2022.01.02 |
Git에서 한 파일의 작업 복사본 수정을 취소하시겠습니까? (0) | 2021.12.31 |
"The breakpoint will not currently be hit. No symbols have been loaded for this document." 를 어떻게 수정합니까? Warning? (0) | 2021.12.31 |
git에서 이름으로 숨김의 이름을 지정하고 검색하는 방법은 무엇입니까? (0) | 2021.12.31 |