Conditional Constructor & Loop(Week 5-2)

G·2022년 10월 7일
0

2-2 OpenSource

목록 보기
6/12
post-thumbnail

Conditional Constructor & Loop

  • Conditional Construct : If / Case statements
  • Loop : While, Until, For, Select

if

예제

#! /bin/bash
NARGS=2
if [ $# -ne $NARGS ]
then
echo "usage: $0 file1 file2"
exit 1 # //0 means succeed
fi
echo "program start"
exit 0
-----------------------------
$ ./ifex.sh a
usage: ./ifex.sh file1 file2
$ echo $?
1
$ ./ifex.sh a b
program start...
$ echo $?
0
#!/bin/bash
account=500
read -p "Enter op:" op
if [ "$op" = "add" ];then
read -p "Enter x to add:" x
result=$((${account} + $x))
echo "Account: ${account} ${op} $x = ${result}"
elif [ "$op" = "sub" ];then
read -p "Enter x to sub:" x
result=$((${account} - $x))
echo "Account: ${account} ${op} $x = ${result}"
else
echo "unknown operator"
fi
------------------------------------------------------
$ ./quiz2.sh 
Enter op:add
Enter x to add:100
Account: 500 add 100 = 600
$ ./quiz2.sh 
Enter op:sub
Enter x to sub:200
Account: 500 sub 200 = 300
$ ./quiz2.sh 
Enter op:mul
unknown operator
$ ./quiz2.sh 
Enter op:
unknown operator

case

#! /bin/bash
read -p "Enter the name of an animal: " ANIMAL
case "$ANIMAL" in
dog|horse|cat)// 셋 중 하나
echo -n "The $ANIMAL has"; echo " 4 legs";;
man)// man
echo -n "Humans have"; echo " 2 legs";;
*)// except all
echo "We don't know" ;;
esac

while

condition이 true일 때 반복문이 실행된다
예제

#!/bin/bash
n=1
while (( n <= 5 )) //as same as [ $n -le 5 ] and you can use true or [blank] to make it infinite
do
echo "Welcome $n times."
n=$(( n+1 )) //as same as let n=n+1
done
$ ./while1.sh 
Welcome 1 times.
Welcome 2 times.
Welcome 3 times.
Welcome 4 times.
Welcome 5 times.

Until

condition이 false일 때만 반복문이 실행된다.
예제

#!/bin/bash
n=1
until [ $n -gt 5 ] //executes when it's false 
do
echo "Welcome $n times." 
let n=n+1
done
----------------------------
$ ./until1.sh 
Welcome 1 times.
Welcome 2 times.
Welcome 3 times.
Welcome 4 times.
Welcome 5 times.

for statement

  • Numbers: for in 1 2 3 4
  • Linux command: for in $(seq 1 5)
  • Strings for in bmw ford
  • File names for in *
  • Command line arguments for in any// arguments are assigned to $(any)

예제

#! /bin/bash
read -p "Enter N:" N
A=0
for K in $( seq 1 $N )
do
echo 2^$K=$(( 2**K ))
A=$(( A + 2**K ))
done
echo $A
---------------------------
$ ./for.sh 
Enter N:2
2^1=2
2^2=4
6
$ ./for.sh
Enter N:5 
2^1=2
2^2=4
2^3=8
2^4=16
2^5=32
62

select

for 반복문에 input이 더해진 반복문이다.
예제

#!/bin/bash
PS3=#?
echo "Pick a fruit, any fruit"
select var in apple pineapple pear orange 
do
echo "$var"
done
-----------------------------------------
# ./select.sh 
Pick a fruit, any fruit
1) apple
2) pear
3) pineapple
4) orange
#? 1
apple
#? 
profile
열심히 안 사는 사람

0개의 댓글