1. 쉘(Shell)이란?
- 쉘(Shell)은 사용자와 커널 사이의 인터페이스로, 명령어를 입력하면 커널이 수행할 수 있도록 해주는 프로그램
- 리눅스에서 가장 많이 사용되는 쉘은 bash (Bourne Again SHell)
2. 쉘 스크립트란?
- 쉘 스크립트(Shell Script)는 쉘 명령어들을 모아 놓은 텍스트 파일
- 즉, 사람이 매번 입력하는 명령어들을 자동으로 순서대로 실행할 수 있도록 작성한 자동화 프로그램
- 확장자는
.sh
가 일반적이지만 필수는 아님
3. 기본 예제
Bash
#!/bin/bash
# 위의 줄은 shebang, 스크립트를 bash로 실행한다는 의미
echo "Hello, World!"
Bash#!/bin/bash
: bash 쉘로 실행하도록 지정
echo
: 문자열 출력
3.1. 실행 방법
Bash
chmod +x script.sh # 실행 권한 부여
./script.sh # 실행
Bash
4. 주요 문법
4.1. 변수 선언
Bash
NAME="Danny"
echo "Hello, $NAME"
Bash- 변수명은 공백 없이
=
로 할당 $변수명
으로 접근
4.2. 명령 실행 파라미터
Bash
./myscript.sh arg1 arg2 arg3
Bash표현 | 의미 |
---|---|
$0 | 스크립트 이름 (myscript.sh ) |
$1 , $2 … | 첫 번째, 두 번째 인자 |
$# | 인자의 개수 |
$@ | 인자 전체 목록 (각각 독립적으로 처리됨) |
$* | 인자 전체 목록 (하나의 문자열로 처리됨) |
4.3. 조건문 (if)
Bash
#!/bin/bash
AGE=10
if [ $AGE -ge 18 ]; then
echo "Adult"
else
echo "Minor"
fi
Bash[ 조건식 ]
또는[[ 조건식 ]]
- 숫자 비교 연산자:
-eq
,-ne
,-lt
,-le
,-gt
,-ge
- 문자열 비교:
=
,!=
Bash
#!/bin/bash
STRING1=abcde
if [ "$STR1"="abcde" ]; then
echo "is 'abcde'"
else
echo "not 'abcde'"
fi
Bash
4.4. 반복문 (for, while)
for문 예시:
Bash
#!/bin/bash
for FILE in *.txt
do
echo "Processing $FILE"
done
Bash실행 결과:
Bash
$ ls -l
run.sh a.txt b.txt c.txt
$ bash run.sh
Processing a.txt
Processing b.txt
Processing c.txt
$
Bash
while문 예시:
Bash
COUNT=1
while [ $COUNT -le 5 ]
do
echo "Count: $COUNT"
COUNT=$((COUNT+1))
done
Bash
4.5. 사용자 입력 받기
Bash
read -p "Enter your name: " USERNAME
echo "Welcome, $USERNAME"
Bash
5. 변수, 환경변수
5.1. Common Bash Environment Variables
Variable | Purpose |
---|---|
PATH | List of directories for finding executables |
HOME | Current user’s home directory |
USER | Current logged-in user |
PWD | Present working directory |
SHELL | Path to the current shell |
LANG | Language and locale |
EDITOR | Default text editor (e.g., vim , nano ) |
TERM | Terminal type (e.g., xterm-256color ) |
5.2. 변수 값 출력하기
Bash
echo $HOME
Bash5.3. 변수 생성하기
Bash
MY_NAME="Danny"
Bash
5.4. 변수를 환경변수로 만들기
Bash
export MY_NAME
Bash- 자식 프로세스에게도 환경변수가 전달됨
6. 함수 정의
- 자주 사용하는 코드를 함수로 정의하여 사용
Bash
function fname() {
echo $1
}
fname "1"
fname "2"
fname "3"
Bash$1
,$2
…은 함수 인자
Bash
$ bash run.sh
1
2
3
Bash6.1. 함수 내 로컬 변수
- 함수 내에서만 존재하고 실행 후에는 사라지는 변수
Bash
#!/bin/bash
function fname() {
local a=100
echo $a
}
fname
echo $a
fname
fname
BashBash
$ bash run.sh
100
100
100
$
Bash6.3. $? : exit status
- command’s return value
Bash
$ ls /aaa
ls: cannot access '/aaa': No such file or directory
$ echo $?
2
$ ls /etc/passwd
/etc/passwd
$ echo $?
0
$ cat run.sh
exit 100
$ bash run.sh
$ echo $?
100
Bash- function’s return value
Bash
#!/bin/bash
function isBiggerThan100() {
if [ $1 -gt 100 ]; then
return 1
else
return 0
fi
}
isBiggerThan100 99
echo $?
isBiggerThan100 101
echo $?
Bash실행결과:
Bash
$ bash f.sh
0
1
Bash
7. Linux Shell Command Operators
>
/>>
(Output Redirection)
2>
,2>&1
,&>
, etc. (Error redirection)<
(Input Redirection)
- && (AND)
- || (OR)
- & (Background)
;
(Sequential execution)
()
(Subshell)
{}
(Command group in current shell)
|
(Pipe)
8. 실용 예제
8.1. 프로세스 자동 재시작
Bash
#!/bin/bash
if ! pgrep nginx > /dev/null
then
echo "Nginx is not running. Restarting..."
systemctl start nginx
fi
Bash
답글 남기기