posted by 귀염둥이채원 2021. 4. 15. 09:43

 

---------------------------------------------------------

# Syntax of for loop:

---------------------------------------------------------

for variable_name in lists; do

commands

done

 

---------------------------------------------------------

# 정적 값 읽기

---------------------------------------------------------

#!/bin/bash

 

for color in Blue Green Pink White Red; do

echo "Color = $color"

done

 

# output

$ bash test.sh

Color = Blue

Color = Green

Color = Pink

Color = White

Color = Red

 

for i in 1 2 3 4 5; do

echo "Welcome $i times"

done

 

# output

$ bash test.sh

Welcome 1 times

Welcome 2 times

Welcome 3 times

Welcome 4 times

Welcome 5 times

 

---------------------------------------------------------

# 배열 변수 읽기

---------------------------------------------------------

#!/bin/bash

ColorList=("Blue Green Pink White Red")

for color in $ColorList; do

if [ $color == 'Pink' ]; then

echo "My favorite color is $color"

fi

done

 

# output

$ bash test.sh

My favorite color is Pink

 

---------------------------------------------------------

# 명령 줄 인수 읽기

---------------------------------------------------------

#!/bin/bash

for myval in $*; do

echo "Argument: $myval"

done

 

# output

$ bash test.sh hello world shell

Argument: hello

Argument: world

Argument: shell

 

---------------------------------------------------------

# 홀수 및 짝수 찾기

---------------------------------------------------------

#!/bin/bash

for ((n = 1; n <= 5; n++)); do

if (($n % 2 == 0)); then

echo "$n is even"

else

echo "$n is odd"

fi

done

 

# output

$ bash test.sh

1 is odd

2 is even

3 is odd

4 is even

5 is odd

 

---------------------------------------------------------

# 구구단 출력

---------------------------------------------------------

#!/bin/sh

 

if [ $# -eq 0 ]; then

echo "Error - Number missing form command line argument"

echo "Syntax : $0 number"

echo "Use to print multiplication table for given number"

exit 1

fi

 

n=$1

 

for (( i = 0; i <= 9; i++ )); do

#for i in 1 2 3 4 5 6 7 8 9; do

echo "$n * $i = $(expr $i \* $n)"

done

 

# output

$ bash test.sh 3

3 * 0 = 0

3 * 1 = 3

3 * 2 = 6

3 * 3 = 9

3 * 4 = 12

3 * 5 = 15

3 * 6 = 18

3 * 7 = 21

3 * 8 = 24

3 * 9 = 27

 

---------------------------------------------------------

# for문 range 설정

---------------------------------------------------------

#!/bin/bash

for i in {1..10}; do

echo $i

done

 

# output

$ bash test.sh

1

2

3

4

5

6

7

8

9

10

 

---------------------------------------------------------

# ls 결과 출력하기

---------------------------------------------------------

#!/bin/bash

for i in $(ls); do

echo $i

done

 

# output

$ bash test.sh

01_tip.sh

02_print.sh

03_variable.sh