[Centos 7] Shell Script 예제
2022. 11. 24. 15:33ㆍ리눅스(Linux)
ShellScript의 구문사용 하기
# if ~ else
# vi ./if_test1.sh
#!/bin/bash
echo -n "Enter ls Command Path: "
read path
if [ -e $path ]; then
echo "ls Command Execution file location: $path"
else
echo "ls Command Execution file Not Found: $path"
fi
# chmod +x ./if_test1.sh
# ./if_test1.sh
Enter ls Command Path: /usr/bin/ls
ls Command Execution file location: /usr/bin/ls
# ./if_test1.sh
Enter ls Command Path: /bin/ls
ls Command Execution file location: /bin/ls
# ./if_test1.sh
Enter ls Command Path: /home/ls
ls Command Execution file Not Found: /home/ls
# vi ./if_test2.sh
#!/bin/bash
echo -n "Input Data: "
read a
if [ $a -gt 0 ]; then
echo $a is 0 More
else
echo $a in 0 Less
fi
# chmod +x ./if_test2.sh
# ./if_test2.sh
Input Data: 100
100 is 0 More
# ./if_test2.sh
Input Data: -10
-10 is 0 less
# vi ./if_test3.sh
#!/bin/bash
echo -n "Input Data: "
read data
if [ $data -ge 0 ]; then
if [ `expr $data % 2` -eq 0 ]; then
echo "Input Data Positive Even Number"
else
echo "Input Data Positive Odd Number"
fi
else
echo "Input Data Negative Number"
fi
# chmod +x ./if_test3.sh
# ./if_test3.sh
Input Data: 100
Input Data Positive Even Number
# ./if_test3.sh
Input Data: 99
Input Data Positive Odd Number
# ./if_test3.sh
Input Data: -10
Input Data Negative Number
# vi ./if_test4.sh
#!/bin/bash
echo -n "Input Your Kor Score: "
read kor
echo -n "Input Your Eng Score: "
read eng
echo -n "Input Your Mat Score: "
read mat
Sum=`expr $kor + $eng + $mat`
Avg=`expr $Sum / 3`
echo ""
echo Your Kor Score: $kor
echo Your Eng Score: $eng
echo Your mat Score: $mat
echo Your Total Score: $Sum
echo Your Average Socre: $Avg
echo ""
if [ $Avg -lt 70 ]; then
echo "Your Average Score: $Avg Fail"
elif [ $kor -lt 60 ]; then
echo "Your Kor Score: $kor Fail"
elif [ $eng -lt 60 ]; then
echo "Your eng Score: $eng Fail"
elif [ $mat -lt 60 ]; then
echo "Your mat Score: $mat Fail"
else
echo "Congratulations on your passing the exam"
fi
# chmod +x ./if_test4.sh
# ./if_test4.sh
Input Your Kor Score: 70
Input Your Eng Score: 70
Input Your Mat Score: 70
Your Kor Score: 70
Your Eng Score: 70
Your mat Score: 70
Your Total Score: 210
Your Average Socre: 70
Congratulations on your passing the exam
#! /bin/bash
echo -n "생성할 계정명을 입력하시오 : "
read _new
echo -n " 생성할 계정이 $_new 가 맞습니까(y/n)? "
read _yes
if [ "$_yes" = Y -o "$_yes" = y ]
then
useradd $_new
fi
# Case
# vi ./case_test1.sh
# chmod +x ./case_test1.sh
#!/bin/bash
echo "Select Menu"
echo "1. Sum"
echo "2. Sub"
echo "3. Mul"
echo "4. Div"
echo -n "Choice Number Input: "
read choice
echo -n "Calc Data Input(2): "
read num1 num2
case $choice in
"1" )
echo "Sum Data: `expr $num1 + $num2`";;
"2" )
echo "Sub Data: `expr $num1 - $num2`";;
"3" )
echo "Mul Data: `expr $num1 \* $num2`";;
"4" )
echo "Div Data: `expr $num1 / $num2`";;
* )
echo "You made a wrong choice";;
esac
# ./case_test1.sh
Select Menu
1. Sum
2. Sub
3. Mul
4. Div
Choice Number Input: 1
Calc Data Input(2): 100 200
Sum Data: 300
# vi ./case_test2.sh
#!/bin/bash
if [ -z $1 ]; then
rental="UnKnown Data"
else
rental=$1
fi
case $rental in
"car" )
echo "$rental Rental Price: 40$";;
"motorcycle" )
echo "$rental Rental Price: 20$";;
"bicycle" )
echo "$rental Rental Price: 10$";;
* )
echo "$rental";;
esac
# chmod +x ./case_test2.sh
# ./case_test2.sh car
car Rental Price: 40$
# ./case_test2.sh motorcycle
motorcycle Rental Price: 20$
# ./case_test2.sh bicycle
bicycle Rental Price: 10$
# ./case_test2.sh
UnKnown Data
$ Select
# vi ./select_test1.sh
#!/bin/bash
PS3="Please Enter Your Choice: "
option=("Coke" "Sprite" "Fanta")
select opt in "${option[@]}"
do
case $opt in
"Coke" )
echo "Coke Price 2000Won" ;;
"Sprite" )
echo "Sprite Price 1800Won" ;;
"Fanta" )
echo "Fanta Price 1500Won" ;;
* )
break ;;
esac
echo "Finished Any Key Enter"
done
# chmod +x ./select_test1.sh
# ./select_test1.sh
1) Coke
2) Sprite
3) Fanta
Please Enter Your Choice: 1
Coke Price 2000Won
Finished Any Key Enter
Please Enter Your Choice: 2
Sprite Price 1800Won
Finished Any Key Enter
Please Enter Your Choice: 3
Fanta Price 1500Won
Finished Any Key Enter
Please Enter Your Choice: 4
- PS3 변수의 경우 select 문에서 사용 할 반복 메시지를 저장하는 용도로 사용 된다.
- 이름은 반드시 PS3로 정의
$ For
# vi ./for_test1.sh
#!/bin/bash
lst='1 2 3 4 5 6 7 8 9 10'
for cnt in $lst
do
echo -n $cnt
done
echo ""
# chmod +x ./for_test1.sh
# ./for_test1.sh
12345678910
# vi ./for_test1.sh
#!/bin/bash
for (( cnt=1;cnt<=10;cnt++ ))
do
echo -n $cnt
done
echo ""
# ./for_test1.sh
12345678910
# vi ./for_test2.sh
#!/bin/bash
arr=(it codeing taehei)
for name in ${arr[@]}
do
echo "$name"
done
[root@MyLinux ~]# chmod +x ./for_test2.sh
[root@MyLinux ~]# ./for_test2.sh
it
codeing
taehei
# vi ./for_test3.sh
#!/bin/bash
for file in $(ls /var/log/*.log)
do
echo " ---- $file ---- "
head -1 $file
echo ""
done
# chmod +x ./for_test3.sh
# ./for_test3.sh
---- /var/log/Xorg.0.log ----
[ 15.471]
---- /var/log/Xorg.9.log ----
[ 8.932]
---- /var/log/boot.log ----
[ OK ] Started Show Plymouth Boot Screen.
---- /var/log/vmware-vmsvc.log ----
[ 2월 19 10:29:08.256] [ message] [vmsvc] Log caching is enabled with maxCacheEntries=4096.
---- /var/log/vmware-vmusr.log ----
[ 2월 19 10:37:03.527] [ message] [vmusr] Log caching is enabled with maxCacheEntries=4096.
---- /var/log/wpa_supplicant.log ----
Successfully initialized wpa_supplicant
---- /var/log/yum.log ----
Feb 24 14:29:45 Updated: 1:quota-nls-4.01-19.el7.noarch
# vi ./for_test4.sh
#!/bin/bash
echo "---- Directory List ----"
echo -n "Input Path: "
read pat
for lst in $(ls $pat)
do
echo $lst
done
# chmod +x ./for_test4.sh
# ./for_test4.sh
---- Directory List ----
Input Path: /home
taehei
user1
# vi ./for_test5.sh
#!/bin/bash
for num in {1..10..2}
do
echo $num
done
# chmod +x ./for_test5.sh
# ./for_test5.sh
1
3
5
7
9
# vi ./for_test6.sh
#!/bin/bash
sum=0
for (( i=1;i<=10;i++ ))
do
sum=`expr $sum + $i`
done
echo "$sum"
# chmod +x ./for_test6.sh
# ./for_test6.sh
55
# vi ./for_test7.sh
for i in 1 2 3 4 5
do
echo $1
done
# chmod +x ./for_test7.sh
# ./for_test7.sh
1
2
3
4
5
$ While
# vi ./while_test1.sh
#!/bin/bash
while [ -f /etc/passwd ]
do
tail -5 /etc/passwd
break
done
# chmod +x ./while_test1.sh
# ./while_test1.sh
avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
ntp:x:38:38::/etc/ntp:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin
itbank:x:1000:1000:itbank:/home/itbank:/bin/bash
# vi ./while_test2.sh
#!/bin/bash
echo -n "Your Password Input: "
read pass
while [ $pass != "1234" ]
do
echo "Plz Enter again"
echo -n "Your Password Input: "
read pass
done
echo "Login Success"
# chmod +x ./while_test2.sh
# ./while_test2.sh
Your Password Input: 1234
Login Success
# ./while_test2.sh
Your Password Input: aaaa
Plz Enter again
Your Password Input: bbbb
Plz Enter again
Your Password Input: 1234
Login Success
[ 로컬 콘솔 터미널 창에서 실행 ]
# firefox
[ Putty 터미널 창에서 스크립트 작성 ]
# vi ./while_test3.sh
#!/bin/bash
echo "==== Process Check! ===="
echo -n "Input Apps Name: "
while read apps
do
if pidof $apps; then
echo -n "Running PID $apps: "
pidof $apps
else
echo "Not Running PID"
fi
echo -n "Exit(0), Continue(1): "
read choice
if [ $choice == 1 ]; then
echo -n "Again Input Apps Name: "
else
echo "Scripts Finished!!"
exit 0
fi
done
# chmod +x ./while_test3.sh
# ./while_test3.sh
==== Process Check! ====
Input Apps Name: firefox
23225
Running PID firefox: 23225
Exit(0), Continue(1): 1
Again Input Apps Name: aaa
Not Running PID
Exit(0), Continue(1): 0
Scripts Finished!!
$ 사용자 정의함수
# vi ./function_test1.sh
#!/bin/bash
function Sum() {
echo "Sum : `expr $num1 + $num2`"
}
echo -n "Enter First Number: "
read num1
echo -n "Enter Second Number: "
read num2
Sum
# ./function_test1.sh
Enter First Number: 100
Enter Second Number: 200
Sum : 300
# vi ./function_test2.sh
#!/bin/bash
function Result() {
if [ $1 -eq "1" ]; then
echo Check [ Ok ]
else
echo Check [ NO ]
fi
}
echo -n "Input Data 1 or 0: "
read num
Result $num
# chmod +x ./function_test2.sh
# ./function_test2.sh
Input Data 1 or 0: 0
Check [ NO ]
# ./function_test2.sh
Input Data 1 or 0: 1
Check [ Ok ]
# vi ./function_test3.sh
#!/bin/bash
func1() {
echo "Func1 is Return Function!!!"
return 100
}
func1
return_val=$?
echo "Func1 Return Value: $return_val"
# chmod +x function_test3.sh
# ./function_test3.sh
Func1 is Return Function!!!
Func1 Return Value: 100
$ ETC
# vi ./eval.sh
#!/bin/bash
str1="uname -sr"
echo -n "Linux System Info: "
eval $str1
cmd_lst="ls /usr/bin | wc -l"
echo -n "Linux Command Count: "
eval $cmd_lst
if [ ! -z $1 ]; then
proc_info="ps -ef | grep $1"
eval $proc_info
else
proc_info="Not Found Aguments"
echo $proc_info
fi
# chmod +x ./eval.sh
# ./eval.sh bash
Linux System Info: Linux 3.10.0-514.el7.x86_64
Linux Command Count: 1587
root 731 1 0 12:39 ? 00:00:00 /bin/bash /usr/sbin/ksmtuned
root 2639 2633 0 12:40 pts/0 00:00:00 -bash
root 6612 6475 0 18:56 ? 00:00:00 /usr/bin/ssh-agent /bin/sh -c exec -l /bin/bash -c "env GNOME_SHELL_SESSION_MODE=classic gnome-session --session gnome-classic"
root 7174 7169 0 18:57 pts/1 00:00:00 bash
root 8536 2639 0 20:26 pts/0 00:00:00 /bin/bash ./eval.sh bash
root 8541 8536 0 20:26 pts/0 00:00:00 grep bash
[ 일반 사용자 계정 "USER"로 접속 후 작업 진행 ]
$ vi ./set_test.sh
#!/bin/bash
echo "Before Error"
cd /root
echo "After Error"
$ chmod +x ./set_test.sh
$ ./set_test.sh
Before Error
./set_test.sh: line 3: cd: /root: 허가 거부
After Error
- 현재 Error가 발생하더라도 스크립트가 계속 실행되는 것을 확인 할 수 있다.
- 스크립트는 중간에 Error가 발생 할 경우 더 이상 실행되지 않는것이 더 효과적이다.
$ vi ./set_test.sh
#!/bin/bash
set -e echo "Before Error"
cd /root
echo "After Error"
$ ./set_test.sh
./set_test.sh: line 3: cd: /root: 허가 거부
- Error가 발생 할 경우 더 이상 스크립트가 실행되지 않는 것을 확인한다.
- Error가 발생 할 것 같은 지점에 "set -e"를 활용한다.
# export MyVAR="Hello World"
# echo $MyVAR
Hello World
# unset MyVAR
# echo $MyVAR
- Unset의 경우 주로 환경변수를 해제할 때 사용된다.
# vi ./command.sh
#!/bin/bash
echo "[ Shadow File 3 Line Check ]"
echo "$(head -3 /etc/shadow)"
echo "Today is $(date)"
# chmod +x ./command.sh
# ./command.sh
[ Shadow File 3 Line Check ]
root:$6$0/FFFZYZ3kpWzby.$56drrKqTK.pw0cAt9Re3EdMIwvTVqokQlg60::0:99999:7:::
bin:*:17110:0:99999:7:::
daemon:*:17110:0:99999:7:::
Today is 2020. 02. 28. (금) 19:40:09 KST
'리눅스(Linux)' 카테고리의 다른 글
[Centos 7] Linux Kernel 관리 (0) | 2022.11.24 |
---|---|
[Centos 7] Linux Crond & Crontab (시스템 예약 작업 크론 ) (0) | 2022.11.24 |
[Centos 7] Shell Programming, shell script (쉘 스크립트) (0) | 2022.11.24 |
[Centos 7] Tar, Gzip and Bzip (압축 도구들) (0) | 2022.11.24 |
[Centos 7] YUM (Yellowdog Updater Manager) (0) | 2022.11.23 |