[1. 개요]
다양한 unix 계열 명령어를 조합하여 실행 할 수 있다.
bash 창에서 직접 입력해나가는 것이 아니라
명령어(혹은 명령어 조합)들을 미리 파일에 작성해두고,
shell 은 이 파일을 읽어서 명령을 수행한다.
[2. 작성 방법]
A. Simple example
#!/bin/bash
# test.sh
echo hello
첫번째 라인이 의미하는 바는
이 스크립트를 실행 할 인터프리터를 명시하는 것이다.
따라서 다음과 같이 작성 할 수 도 있다.
#!/usr/local/bin/python
num=3
for i in range(num):
print(i)
최초 작성 한 파일에 퍼미션에는 실행 권한이 없으므로,
chmod 명령어를 이용해서 실행 권한을 부여한다.
또는, 다음과 같이 명령어를 작성하여 실행 할 수 있다,
$ bash test.sh
B. 변수 사용
C. if 문
#!/bin/bash -x
# Compare string.
if [[ "$1" == "" ]]; then
echo empty param.
elif [[ "$1" == "--help" ]]; then
echo this is help message.
else
echo your input $1
fi
# Compare integer
if [[ $2 == 11 ]]; then
echo eleven
else
echo not eleven
fi
# etc example
if [[ "$3" == "" ]]; then
echo empty param2
elif [[ -d $3 ]]; then # Is this directory?
echo $3 is directory
elif [[ -e $3 ]]; then # Is this file?
echo $3 is file
elif [[ "$3" == *.zip ]]; then # careful!
echo $3 is zip
else
echo the other...
fi
D. 반복문
bash shell 스크립트 기준으로 아래와 같이 C++ 형태의 반복문을 구성할 수 있다.
#!/bin/bash
for ((i=0; i<10; i++)); do
printf "%02d\n" $i
done
POSIX 표준은 다음과 같다.
# 표준 작성 방식
# list 에는 $(...) 와 같은 명령어가 올 수 있다.
# for var in list; do
# commands
# done
#!/bin/sh
for i in $(seq 0 9); do
printf "%02d\n" $i
done
특히, 쉘 프롬프트 자체에서 for 문 을 사용해야 할 경우 아래와 같이 할 수 있다.
$ for ((i=0; i<10; i++)); do printf "%02d\n" $i; done
$ for i in $(seq 0 9); do printf "%02d\n" $i; done
$ for i in $(seq 0 9); do t=$(printf "%02d\n" $i); touch $t; done
[3. ]
'리눅스 > shell' 카테고리의 다른 글
| bash shell 실행 옵션 (0) | 2025.09.16 |
|---|---|
| [shell, 내용보강하도록] 배열 (1) | 2024.04.03 |