Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags
more
Archives
Today
Total
관리 메뉴

클라우드 엔지니어 꿈나무

Redhat RH-134 : 인용 특수 문자 + BASH 스크립트 + for문 본문

Linux

Redhat RH-134 : 인용 특수 문자 + BASH 스크립트 + for문

새싹싹이 2023. 10. 16. 20:09

인용 특수 문자

특별한 의미가 아닌 리터럴 값으로 사용해야 하려면 스크립트에서 해당 문자를 이스케이프 해야함

이케이프를 위하여 (\),(''),("") 사용

# echo # not a comment

# echo \# not a comment

# echo \# not a comment \#
# echo '# not a comment #' 

변수에는 중괄호 쓰는 것이 권장사항

$ var=$(hostname -s); echo $var => 단축된 호스트명을 var라는 변수에 할당하여 불러옴

$ id

$ echo $PATH  => 명령어 path 확인

하기 경로에 명령어 추가하면 실행 가능

 

 

BASH 스크립트

path 에 명령어 넣어 실행하기 1

$ vim data

#!/usr/bin/bash

echo "Hate Monday"

$ mkdir /home/student/bin

$ mv monday /home/student/bin

$ cd /home/student/bin

$ ls -al monday

$ chmod u+x monday

$ monday

$ which 명령어가 어디에 있는지 확인

$ which monday  

<<참고>> => 

# which httpd => $PATH 내에서 명령어의 실행 가능한 파일 경로 c-검색

# whereis httpd => 명령어 실행 파일, 매뉴얼 페이지, 소스 코드 위치를 모두 표시

 


vim 편집기

p 붙여넣기

3 dd =>  3줄 잘라내기

y 복사하기

#!/bin/bash => bash shell로 만들었다는 뜻

 


# echo

# \#test user

$ uname -r => Unixname kernel version 확인

$ df -h => 디스크 사용량 보기 쉽게 표기

$ free => 메모리 확인

path 에 명령어 넣어 실행하기 2

$ vim firstscript.sh

#!/usr/bin/bash
#
echo "This is my first bash script" > ~/output.txt
echo "" >> ~/output.txt
echo "#####################################################" >> ~/output.txt
echo "LIST BLOCK DEVICES" >> ~/output.txt
echo "" >> ~/output.txt
lsblk >> ~/output.txt
echo "" >> ~/output.txt
echo "#####################################################" >> ~/output.txt
echo "FILESYSTEM FREE SPACE STATUS" >> ~/output.txt
echo "" >> ~/output.txt
df -h >> ~/output.txt
echo "#####################################################" >> ~/output.txt

$ chmod a+x firstscript.sh

$ ./firstcript.sh => output.txt 생성 됨

$ cat output.txt

 

반복문 (for문)

for VARIABLE in LIST; do

COMMAND VARIABLE

done

$ for test in {1..5}; do; echo $test; echo ""; done

 

$ for i in {1..100}

> do

> touch oradata$i

>done

 

Bash 스크립트 종료(상태) 코드

exit 명령은 종료 코드를 나타내는 0과 255 사이의 선택적 정수 인수와 함께 사용

0 => 스크립트 오류 없이 완료되었음

그 외 숫자 => 오료 종료 코드 

# echo $? => 이전 명령어에 대한 상태 코드

$ test 1 -gt 0 ; echo $? => gt(greater) 1이 0보다 큰가? 

$ test 0 -gt 1 ; echo $?

0 => 위의 조건문이 참이기 때문에 0으로 표시

$ systemctl is-active sshd

active

$ echo $?

0 => 정상적으로 작동중이면 0을 반환

 

연습 가이드

$ ssh student@servera hostname

$ ssh student@serverb hostname

위의 구문을 <for 문 + 상태 코드 출력>으로 명령어 생성

#!/usr/bin/bash
#Execute for loop to print server hostname
for HOST in servera serverb
do
        ssh student@${HOST} hostname
done
exit 0

$ chmod u+x ~/bin/printhostname.sh

$ printhostname.sh

$ echo $?