본문 바로가기

리눅스/shell

shell script 기초

[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. 반복문

 

 

[3. ]

'리눅스 > shell' 카테고리의 다른 글

[shell, 내용보강하도록] 배열  (1) 2024.04.03