본문 바로가기

System/Linux

[리눅스] 리눅스 bash shell_기본 문법

반응형

1. shell script 파일 생성

쉘 스크립트 파일 생성한다.

ex) vim [filename.sh]

 

2. shell script 첫번째 구문 작성

첫번째 줄에 #! /bin/bash를 입력한다.

ex) #! /bin/bash

 

3. shell scrip 데이터 출력문

문자열 데이터 출력할 때 echo및 printf 사용한다.

$# : 스크립트에 전달되는 인자들의 수

$0 : 실행하는 스크립트 파일명으로 실행했을 때 경로를 입력했다면 경로를 출력

$1, $2... : 스크립트로 전달된 인자들

ex) echo "[출력문]"

ex) printf "[출력문]"

결과 출력 : 

 

4. shell scrip 저장

vim명령어를 wq를 이용하여 저장한다.

ex) :wq

 

5. shell script 실행

chmod명령어를 사용하여 권한을 부여한다.

ex) chmod +x [bash shell script filename.sh]

script 실행

ex) ./[bash shell scrip filename.sh]

 

6. shell script 변수선언 및 출력

변수 선언

ex) [변수명]=[변수값]

변수 출력

ex) echo "a=$[변수명]"

출력 결과 : 

7. shell script 값 입력받기

사용자로 부터 값을 입력 받기 위해서 read를 사용한다.

ex) read [변수명]

출력 결과 : 

 

8. shell script 사칙연산

덧셈 : +

뺄셈 : -

곱셈 : *

나눗셈 : /

나머지 : % 

조건 :

1) expr 사용시 역쿼테이션(') 사용

2) 곱셈 연산자 기호 * 앞에 역슬래시(\)를 같이 사용

3) 모든 연산자와 숫자, 변수, 기호 사이에는 공백이 존재

출력 결과 : 

 

9. shell script 조건문(IF)

IF문

if [조건]; then

...

elif[조건]; then

...

else

...

fi

※ 조건문 참고 URL

https://wiki.kldp.org/HOWTO/html/Adv-Bash-Scr-HOWTO/comparison-ops.html

 

비교 연산자(이진)

#!/bin/bash # str-test.sh: Testing null strings and unquoted strings, # but not strings and sealing wax, not to mention cabbages and kings... # (옮긴이: ??? :) # if [ ... ] 를 쓸께요. # 문자열이 초기화 안 됐다면 정해진 값을 갖지 ��

wiki.kldp.org

codewiki.wikidot.com/shell-script:if-else

 

If / Else Statements (Shell Scripting) - Code Wiki

If / Else Statements (Shell Scripting) Shell scripts use fairly standard syntax for if statements. The conditional statement is executed using either the test command or the [ command. In its most basic form an if statement is: #!/bin/bash if [ "$#" -gt 0

codewiki.wikidot.com

10. shell script 반복문(while, for)

1) for문

ex)

for 변수 in 반복조건

do

...

done

 

※ for문 참고 URL

wikidocs.net/32168

 

위키독스

온라인 책을 제작 공유하는 플랫폼 서비스

wikidocs.net

 

2) while문

ex) 

while [값1 조건식 값2]

do

...

done

 

※ while문 참고 URL

wikidocs.net/29981

 

위키독스

온라인 책을 제작 공유하는 플랫폼 서비스

wikidocs.net

11. shell script 주석

#을 사용한다.

 

12. shell script 배열

배열의 인덱스는 0부터 시작이다.

배열이름[@] : 모든 원소

+= : 배열에 원소 추가

/ : 해당 문자열 부분이 있으면 삭제, 삭제하고자 하는 문자나 문자열이 포함시 모두 삭제

unset : 삭제

ex) 배열이름=("원소1" "원소2" "원소3" ...) 

ex) 변수명+=("원소1" "원소2")

ex) 변수명=("${변수명[@]/$삭제문자및삭제할문자열이저장된변수}")

ex) unset 변수명[i]

반응형