Bash script: Difference between revisions

From HPCWIKI
Jump to navigation Jump to search
(Add categories: Linux, Reference)
(Phase 6.1: LLM-Optimized Wiki Template 적용)
Line 1: Line 1:
A summary for some important Bash scripts
{{Status
|status=Draft
|owner=Knowledge Agent
|last_update=2026-07-16
|review=Pending
}}
 
{{TOC}}
 
== Overview ==
 
Bash 스크립트는 Linux/Unix 시스템에서 명령어를 자동화하고 작업을 효율적으로 관리하기 위한 스크립트 언어입니다.
 
=== Summary ===
 
* 무엇인가? Linux/Unix 명령어 자동화 스크립트 언어
* 왜 필요한가? 반복 작업 자동화, 시스템 관리, 배치 처리
* 언제 사용하는가? 서버 설정, 로그 분석, 백업, 배포 등
 
---
 
== Purpose ==
 
이 문서가 존재하는 이유
 
* Goal: Bash 스크립트의 주요 명령어, special parameters, set 옵션 설명 제공
* Scope: set 명령어 옵션, bash special parameters
* Non-goals: Bash 프로그래밍 상세, 함수/배열/제어문
 
---
 
== Key Concepts ==
 
{| class="wikitable"
{| class="wikitable"
|+
! Concept
!Command
! Description
!Description
! Related
|-
| Bash
| Bourne Again Shell — Linux 기본 셸
| [[Linux]]
|-
| set
| 셸 옵션 활성화/비활성화 명령어
| [[Bash script]]
|-
| special parameters
| $*, $@, $#, $?, $$ 등 특수 매개변수
| [[Bash script]]
|-
| IFS
| Internal Field Separator — 필드 구분자
| [[Bash script]]
|-
|-
|set
| positional parameters
|'''set [options] [arguments]'''<ref>https://linuxhint.com/set-command-bash/</ref>  
| $1, $2, $3... — 위치 매개변수
sign (-) is used with the command’s option to enable that option and the plus sign (+) is used with the command’s option to disable that option
| [[Bash script]]
{| class="wikitable"
|}
| -a
 
|It defines those variables or functions which are created or modified or exported
---
Example, These variables v1 and v2 can be accessed after executing the script
 
<code>#!/bin/bash</code>
== Architecture ==
 
Bash 스크립트 실행 프로세스:
 
<syntaxhighlight lang="mermaid">
graph TD
    A[Bash 스크립트 파일] --> B[Bash 인터프리터]
    B --> C[명령어 파싱]
    C --> D[변수 설정]
    D --> E[조건/반복문]
    E --> F[명령어 실행]
    F --> G[결과 반환]
</syntaxhighlight>
 
---
 
== Workflow ==
 
Bash 스크립트 기본 워크플로우:
 
# 스크립트 작성
# #!/bin/bash
# 명령어 작성
# 실행 권한 부여
# chmod +x script.sh
# 스크립트 실행
# ./script.sh


<code>#Enable -a option to read the values of the variables</code>
---


<code>set -a</code>
== Detailed Explanation ==


<code>#Initialize three variables</code>
=== set 명령어 ===


<code>v1=78</code>
set 명령어는 셸 옵션을 활성화(-) 또는 비활성화(+)합니다.


<code>v2=50</code>
{| class="wikitable"
! 옵션
! 설명
! 예제
|-
| -a
| 생성/수정/내보낸 변수 또는 함수 정의
| <code>set -a</code> — 변수 값 읽기 활성화
|-
|-
| -b
| -b
|It informs the job termination.
| 작업 종료를 알림
| —
|-
|-
| -B
| -B
|To do the task of the brace expansion.
| 중괄호 확장(brace expansion) 작업 수행
| —
|-
|-
| -C
| -C
|It disables the overwriting feature of the existing file
| 기존 파일 덮어쓰기 기능 비활성화
Example,
| <code>set -C</code> — <code>cat > testfile.txt</code> 덮어쓰기 방지
$ cat > testfile.txt
 
$ set -C
 
$ cat > testfile.txt.  # Could not overwrite testfile.txt
|-
|-
| -e
| -e
|It exits for non-zero exit status value.
| 0이 아닌 종료 상태 값에서 즉시 종료
| <code>set -e</code> — 에러 시 스크립트 중단
|-
|-
| -f
| -f
|It disables the filename generation task.
| 파일명 생성(task) 비활성화
| —
|-
|-
| -h
| -h
|It saves the location of the command where it has been used.
| 명령어 위치 저장
| —
|-
|-
| -m
| -m
|It enables job control.
| 작업 제어(job control) 활성화
| —
|-
|-
| -n
| -n
|It reads the commands.
| 명령어만 읽기 (실행 안 함)
| —
|-
|-
| -t
| -t
|It exits from the command after executing a single command.
| 단일 명령어 실행 후 종료
| —
|-
|-
| -u
| -u
|It traces the unset variables - error is printed for the uninitialized variable
| 설정되지 않은 변수 추적 — 초기화되지 않은 변수에 대해 에러 출력
| <code>set -u</code> — 미설정 변수 에러
|-
|-
| -v
| -v
|It prints the shell input lines.
| 셸 입력 줄 출력
| —
|-
|-
| -x
| -x
|It displays the commands and their attributes sequentially. It is mainly used to debug the script.
| 명령어와 속성을 순차적으로 표시 — 주로 디버깅용
| <code>set -x</code> — 디버깅 모드
|-
|-
| -- variable
| -- variable
|The string value is divided into three parts based on the space that is printed
| 문자열 값을 공백 기준으로 3개 부분으로 분할
<nowiki>#</nowiki>!/bin/bash
| <code>set -- $myvar</code>
|}


<nowiki>#</nowiki>Define a string variable
'''set 명령어 종료 값:'''


myvar="Learn bash programming"
* '''0''' — 작업 성공 완료
* '''1''' — 유효하지 않은 인수로 실패
* '''1''' — 누락된 인수로 실패


<nowiki>#</nowiki>Set the set command without option and with variable
=== bash special parameters ===


set -- $myvar
{| class="wikitable"
 
! 매개변수
<nowiki>#</nowiki>Print the split value
! 설명
 
! 예제
printf "$1\n$2\n$3\n"
|}
'''Exit Values of Set Command'''
 
# Zero (0) is returned to complete the task successfully.
# One (1) is returned if a failure occurs for any invalid argument.
# One (1) is returned if a failure occurs for a missing argument.
|}
 
== bash special parameters<ref>https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html</ref> ==
{| class="wikitable sortable"
!parameters
!Description
!Example
|-
|-
|<code>*</code>
| <code>*</code>
|($*) Expands to the positional parameters, starting from one. When the expansion is not within double quotes, each positional parameter expands to a separate word. In contexts where it is performed, those words are subject to further word splitting and filename expansion. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the <code>IFS</code> special variable. That is, <code>"$*"</code> is equivalent to <code>"$1<var>c</var>$2<var>c</var>…"</code>, where <var>c</var> is the first character of the value of the <code>IFS</code> variable. If <code>IFS</code> is unset, the parameters are separated by spaces. If <code>IFS</code> is null, the parameters are joined without intervening separators.
| <code>$*</code> — 위치 매개변수를 1부터 확장. 더블 쿼트 내에 있으면 IFS 첫 문자로 연결된 단일 단어
|
| <code>"$*"</code> <code>"$1$c$2$c..."</code> (c는 IFS 첫 문자)
|-
|-
|<code>@</code>
| <code>@</code>
|($@) Expands to the positional parameters, starting from one. In contexts where word splitting is performed, this expands each positional parameter to a separate word; if not within double quotes, these words are subject to word splitting. In contexts where word splitting is not performed, this expands to a single word with each positional parameter separated by a space. When the expansion occurs within double quotes, and word splitting is performed, each parameter expands to a separate word.  That is, <code>"$@"</code> is equivalent to <code>"$1" "$2" …</code>. If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, <code>"$@"</code> and <code>$@</code> expand to nothing (i.e., they are removed).
| <code>$@</code> — 각 위치 매개변수를 별도 단어로서 확장
|
| <code>"$@"</code> <code>"$1" "$2" ..."</code>
|-
|-
|<code>#</code>
| <code>#</code>
|($#) Expands to the number of positional parameters in decimal.
| 위치 매개변수 개수
|
| <code>$#</code> — 전달된 인수 개수
|-
|-
|<code>?</code>
| <code>?</code>
|($?) Expands to the exit status of the most recently executed foreground pipeline.
| 직전 명령어의 종료 상태
|
| <code>$?</code> — 0=성공, 0이 아님=실패
|-
|-
|<code>-</code>
| <code>$</code>
|($-, a hyphen.)  Expands to the current option flags as specified upon invocation, by the <code>set</code> builtin command, or those set by the shell itself (such as the <samp>-i</samp> option).
| 스크립트 PID
|
| <code>$$</code> — 현재 프로세스 ID
|-
|-
|<code>$</code>
| <code>-</code>
|($$) Expands to the process <small>ID</small> of the shell.  In a subshell, it expands to the process <small>ID</small> of the invoking shell, not the subshell.
| 활성화된 셸 옵션
|Determine the Current Shell
| <code>$-</code> — 현재 셸 플래그
<$ readlink /proc/$$/exe
/usr/bin/bash</code>
$ cat /proc/$$/cmdline
<code>bash</code>
|-
|-
|<code>0</code>
| <code>!</code>
|($0) Expands to the name of the shell or shell script.  This is set at shell initialization.  If Bash is invoked with a file of commands (see Shell Scripts), <code>$0</code> is set to the name of that file. If Bash is started with the <samp>-c</samp> option (see Invoking Bash), then <code>$0</code> is set to the first argument after the string to be executed, if one is present. Otherwise, it is set to the filename used to invoke Bash, as given by argument zero.  
| 직전 백그라운드 작업의 PID
|Determine the Current Shell
| <code>$!</code> — 마지막 백그라운드 작업 PID
|}
 
---
 
== Configuration ==
 
=== Bash 스크립트 기본 설정 ===
 
<syntaxhighlight lang="bash">
#!/bin/bash
 
# 에러 시 종료
set -e
 
# 미설정 변수 에러
set -u
 
# 디버깅 모드 (필요시)
# set -x
 
# 변수 정의
myvar="Hello World"
 
# 위치 매개변수 사용
echo "첫 번째 인수: $1"
echo "두 번째 인수: $2"
echo "인수 개수: $#"
</syntaxhighlight>
 
---
 
== Examples ==
 
=== Example 1: set 명령어 사용 ===
 
입력:
 
<syntaxhighlight lang="bash">
#!/bin/bash
set -a
v1=78
v2=50
echo "v1=$v1, v2=$v2"
</syntaxhighlight>
 
출력:
 
<syntaxhighlight lang="bash">
v1=78, v2=50
</syntaxhighlight>
 
=== Example 2: special parameters ===
 
입력:
 
<syntaxhighlight lang="bash">
#!/bin/bash
myvar="Learn bash programming"
set -- $myvar
printf "$1
$2
$3
"
</syntaxhighlight>
 
출력:
 
<syntaxhighlight lang="bash">
Learn
bash
programming
</syntaxhighlight>
 
---
 
== Best Practices ==
 
* '''set -e 사용''' — 에러 시 스크립트 즉시 중단 (안정성)
* '''set -u 사용''' — 미설정 변수 에러 감지 (버그 방지)
* '''set -x 사용''' — 디버깅 시 명령어 추적 (개발 단계)
* '''"$@" 사용''' — <code>"$*"</code>보다 <code>"$@"</code> 권장 (인수 분리 유지)
* '''#!/bin/bash 명시''' — 스크립트 첫 줄에 인터프리터 명시
 
---
 
== Limitations ==
 
* Bash는 스크립트 언어 — 대규모 애플리케이션에는 부적합
* Python/Perl 등 대체 언어가 더 많은 기능 제공
* POSIX 호환성 문제 — Bash 특화 기능은 다른 셸에서 작동 안 함
 
---
 
== References ==
 
* https://linuxhint.com/set-command-bash/
* https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html
 
---
 
== Related Pages ==


<$ echo $0
* [[Linux]]
bash</code>
* [[systemd]]
|-
* [[Bazel]]
|!
* [[Cmake tips and tricks]]
|($!) Expands to the process <small>ID</small> of the job most recently placed into the background, whether executed as an asynchronous command or using the <code>bg</code> builtin (see Job Control Builtins).
 
|
---
|}


== Reference ==
<references/>
[[Category:Linux]]
[[Category:Linux]]
[[Category:Reference]]
[[Category:Reference]]

Revision as of 14:33, 16 July 2026

Template:Status

Template:TOC

Overview

Bash 스크립트는 Linux/Unix 시스템에서 명령어를 자동화하고 작업을 효율적으로 관리하기 위한 스크립트 언어입니다.

Summary

  • 무엇인가? Linux/Unix 명령어 자동화 스크립트 언어
  • 왜 필요한가? 반복 작업 자동화, 시스템 관리, 배치 처리
  • 언제 사용하는가? 서버 설정, 로그 분석, 백업, 배포 등

---

Purpose

이 문서가 존재하는 이유

  • Goal: Bash 스크립트의 주요 명령어, special parameters, set 옵션 설명 제공
  • Scope: set 명령어 옵션, bash special parameters
  • Non-goals: Bash 프로그래밍 상세, 함수/배열/제어문

---

Key Concepts

Concept Description Related
Bash Bourne Again Shell — Linux 기본 셸 Linux
set 셸 옵션 활성화/비활성화 명령어 Bash script
special parameters $*, $@, $#, $?, $$ 등 특수 매개변수 Bash script
IFS Internal Field Separator — 필드 구분자 Bash script
positional parameters $1, $2, $3... — 위치 매개변수 Bash script

---

Architecture

Bash 스크립트 실행 프로세스:

graph TD
    A[Bash 스크립트 파일] --> B[Bash 인터프리터]
    B --> C[명령어 파싱]
    C --> D[변수 설정]
    D --> E[조건/반복문]
    E --> F[명령어 실행]
    F --> G[결과 반환]

---

Workflow

Bash 스크립트 기본 워크플로우:

  1. 스크립트 작성
  2. #!/bin/bash
  3. 명령어 작성
  4. 실행 권한 부여
  5. chmod +x script.sh
  6. 스크립트 실행
  7. ./script.sh

---

Detailed Explanation

set 명령어

set 명령어는 셸 옵션을 활성화(-) 또는 비활성화(+)합니다.

옵션 설명 예제
-a 생성/수정/내보낸 변수 또는 함수 정의 set -a — 변수 값 읽기 활성화
-b 작업 종료를 알림
-B 중괄호 확장(brace expansion) 작업 수행
-C 기존 파일 덮어쓰기 기능 비활성화 set -Ccat > testfile.txt 덮어쓰기 방지
-e 0이 아닌 종료 상태 값에서 즉시 종료 set -e — 에러 시 스크립트 중단
-f 파일명 생성(task) 비활성화
-h 명령어 위치 저장
-m 작업 제어(job control) 활성화
-n 명령어만 읽기 (실행 안 함)
-t 단일 명령어 실행 후 종료
-u 설정되지 않은 변수 추적 — 초기화되지 않은 변수에 대해 에러 출력 set -u — 미설정 변수 에러
-v 셸 입력 줄 출력
-x 명령어와 속성을 순차적으로 표시 — 주로 디버깅용 set -x — 디버깅 모드
-- variable 문자열 값을 공백 기준으로 3개 부분으로 분할 set -- $myvar

set 명령어 종료 값:

  • 0 — 작업 성공 완료
  • 1 — 유효하지 않은 인수로 실패
  • 1 — 누락된 인수로 실패

bash special parameters

매개변수 설명 예제
* $* — 위치 매개변수를 1부터 확장. 더블 쿼트 내에 있으면 IFS 첫 문자로 연결된 단일 단어 "$*""$1$c$2$c..." (c는 IFS 첫 문자)
@ $@ — 각 위치 매개변수를 별도 단어로서 확장 "$@""$1" "$2" ..."
# 위치 매개변수 개수 $# — 전달된 인수 개수
? 직전 명령어의 종료 상태 $? — 0=성공, 0이 아님=실패
$ 스크립트 PID $$ — 현재 프로세스 ID
- 활성화된 셸 옵션 $- — 현재 셸 플래그
! 직전 백그라운드 작업의 PID $! — 마지막 백그라운드 작업 PID

---

Configuration

Bash 스크립트 기본 설정

#!/bin/bash

# 에러 시 종료
set -e

# 미설정 변수 에러
set -u

# 디버깅 모드 (필요시)
# set -x

# 변수 정의
myvar="Hello World"

# 위치 매개변수 사용
echo "첫 번째 인수: $1"
echo "두 번째 인수: $2"
echo "인수 개수: $#"

---

Examples

Example 1: set 명령어 사용

입력:

#!/bin/bash
set -a
v1=78
v2=50
echo "v1=$v1, v2=$v2"

출력:

v1=78, v2=50

Example 2: special parameters

입력:

#!/bin/bash
myvar="Learn bash programming"
set -- $myvar
printf "$1
$2
$3
"

출력:

Learn
bash
programming

---

Best Practices

  • set -e 사용 — 에러 시 스크립트 즉시 중단 (안정성)
  • set -u 사용 — 미설정 변수 에러 감지 (버그 방지)
  • set -x 사용 — 디버깅 시 명령어 추적 (개발 단계)
  • "$@" 사용"$*"보다 "$@" 권장 (인수 분리 유지)
  • #!/bin/bash 명시 — 스크립트 첫 줄에 인터프리터 명시

---

Limitations

  • Bash는 스크립트 언어 — 대규모 애플리케이션에는 부적합
  • Python/Perl 등 대체 언어가 더 많은 기능 제공
  • POSIX 호환성 문제 — Bash 특화 기능은 다른 셸에서 작동 안 함

---

References

---

Related Pages

---