developer tip

bash에서 for 루프를 작성하는 방법

optionbox 2020. 9. 13. 10:23
반응형

bash에서 for 루프를 작성하는 방법


다음과 같은 기본 루프를 찾고 있습니다.

for(int i = 0; i < MAX; i++) {
  doSomething(i);
}

하지만 bash를 위해.


에서 이 사이트 :

for i in $(seq 1 10);
do
    echo $i
done

for ((i = 0 ; i < max ; i++ )); do echo "$i"; done

bash for는 변수 (반복자)와 반복자가 반복 할 단어 목록으로 구성됩니다.

따라서 제한된 단어 목록이있는 경우 다음 구문에 입력하십시오.

for w in word1 word2 word3
do
  doSomething($w)
done

아마도 일부 숫자를 따라 반복하고 싶을 것이므로 seq명령을 사용하여 숫자 목록을 생성 할 수 있습니다. (예 : 1에서 100까지)

seq 1 100

FOR 루프에서 사용하십시오.

for n in $(seq 1 100)
do
  doSomething($n)
done

$(...)구문에 유의하십시오 . 그것은 당신이 (에서 우리의 경우 한 명령의 출력을 전달할 수, 강타 행동의 seq다른를)합니다 ( for)

이것은 어떤 경로의 모든 디렉토리를 반복해야 할 때 매우 유용합니다. 예를 들면 다음과 같습니다.

for d in $(find $somepath -type d)
do
  doSomething($d)
done

목록 생성 가능성은 무한합니다.


Bash 3.0 이상 에서는 다음 구문을 사용할 수 있습니다.

for i in {1..10} ; do ... ; done

.. 시퀀스를 확장하기 위해 외부 프로그램을 생성하지 않습니다 (예 :) seq 1 10.

물론 이것은 for(())솔루션 과 동일한 문제를 가지고 있으며 bash 및 특정 버전에 묶여 있습니다 (이게 중요하다면).


bash기본 제공 도움말을 사용해보십시오 .


$ help for

for: for NAME [in WORDS ... ;] do COMMANDS; done
    The `for' loop executes a sequence of commands for each member in a
    list of items.  If `in WORDS ...;' is not present, then `in "$@"' is
    assumed.  For each element in WORDS, NAME is set to that element, and
    the COMMANDS are executed.
for ((: for (( exp1; exp2; exp3 )); do COMMANDS; done
    Equivalent to
        (( EXP1 ))
        while (( EXP2 )); do
            COMMANDS
            (( EXP3 ))
        done
    EXP1, EXP2, and EXP3 are arithmetic expressions.  If any expression is
    omitted, it behaves as if it evaluates to 1.



나는 일반적으로 표준 for 루프에서 약간의 변형을 사용하는 것을 좋아합니다. 나는 종종 이것을 사용하여 일련의 원격 호스트에서 명령을 실행합니다. bash의 중괄호 확장을 이용하여 숫자가 아닌 for 루프를 만들 수있는 for 루프를 만듭니다.

예:

프런트 엔드 호스트 1-5와 백엔드 호스트 1-3에서 uptime 명령을 실행하고 싶습니다.

% for host in {frontend{1..5},backend{1..3}}.mycompany.com
    do ssh $host "echo -n $host; uptime"
  done

I typically run this as a single-line command with semicolons on the ends of the lines instead of the more readable version above. The key usage consideration are that braces allow you to specify multiple values to be inserted into a string (e.g. pre{foo,bar}post results in prefoopost, prebarpost) and allow counting/sequences by using the double periods (you can use a..z etc.). However, the double period syntax is a new feature of bash 3.0; earlier versions will not support this.


#! /bin/bash

function do_something {
   echo value=${1}
}

MAX=4
for (( i=0; i<MAX; i++ )) ; {
   do_something ${i}
}

Here's an example that can also work in older shells, while still being efficient for large counts:

Z=$(date) awk 'BEGIN { for ( i=0; i<4; i++ ) { print i,"hello",ENVIRON["Z"]; } }'

But good luck doing useful things inside of awk: How do I use shell variables in an awk script?


if you're intereased only in bash the "for(( ... ))" solution presented above is the best, but if you want something POSIX SH compliant that will work on all unices you'll have to use "expr" and "while", and that's because "(())" or "seq" or "i=i+1" are not that portable among various shells


I use variations of this all the time to process files...

for files in *.log; do echo "Do stuff with: $files"; echo "Do more stuff with: $files"; done;

If processing lists of files is what you're interested in, look into the -execdir option for files.

참고URL : https://stackoverflow.com/questions/49110/how-do-i-write-a-for-loop-in-bash

반응형