티스토리 뷰

IoT 과정

POSIX Shell Programming

gaelim 2017. 7. 5. 10:38
반응형

unix가 command 찾는 순서

1. alias

2. built-in or keyword

3. $PATH  : 출력되는 경로 순부터 커맨드를 찾는다. short circuit. 경로 맨 뒤에는 현재 디렉토리 . 도 포함되어 있는 것을 확인할 수 있다. type, ls, cd 등의 파일을 현재디렉토리에 생성하고 실행하려해도 short circuit 때문에 작동하지 않는다.

이 세 순서로 찾은 뒤 없으면 command not found 라고 뜬다.

참고 : $변수 입력 뒤 캐리지리턴시 substitution이 일어나 echo 커맨드를 발생. 또다른 예는 rm *. 오래된 유닉스 시스템 사용 시, 파일이 너무많을경우 rm * 수행시 command too long 에러를 터미널 화면에 리턴함.


Shell Script는 external cmd이다. 이 command를 수행시키는 방법은 두 가지이다.

1. $PATH에 파일 경로를 제시하기 

2. 수행시 경로를 제시하기 (eg. ./myProg) 이 방법은 command 찾기의 0번이므로 alias, ascii


external cmd는 binary, ascii text 로 이루어져있다. bin는 *.c, *.java 등 컴파일러로 컴파일 한 파일이므로 vi 파일로 편집할 수 없다. ascii text는 shell 인터프리터로 번역하는 파일이다. shell script 이며 vi 파일로 편집할 수 있다. 기존에 사용하는 파일들을 작성한 언어가 컴파일 언어인지 스크립트 언어인지 확인하는 방법은 /usr/bin 경로로 이동 후 file * 수행. ELF-32, 64 는 컴파일 된 파일, commands text는 script 파일이다.


Script Execution

1 Create a text file containing at least one command

vi myprog.sh

banner "hello world"

date


2 Close the file

:wq


3 Add execute permission to the file 

chmod (u)+x myprog.sh


4 Execute (run) the file

./myprog.sh


External Infulences on the Script

 스크립트 수행시 자식 쉘이 생성된다. 따라서 다음과 같은 파일은 원하는대로 수행하지 않는다.

$ cat > xx.sh

xx=111

$ chmod +x xx.sh

$ ./xx.sh

$ $xx

sh: xx: Parameter not set.


원하는 바로 하려면 본 쉘에서 수행해야한다. source, 소싱한다고 함.
$ . ./xx.sh
$ echo $xx
111

What Happens after "Enter?"

1 The shell interprets your command line
2 The shell performs any substitution  //*, ?, ~, [ ] ... 등등
3 The shell locates your program
...  command 수행 전에 일어나는 substitution 그리고 locates program의 예
$ touch echo xxx yyy zzz  //4개의 파일 생성
$ echo *
$ echo xxx yyy zzz
$ *
$ xxx yyy zzz
...
4 The shell sets up I/O redirection // <, >, |, 입출력을 어디로 할지 판단
5 The shell invokes your program // bin, ascii text인지 판단하여 직접 수행(bin 경우) 또는 어떤 인터프리터(script 경우)로 넘길지 판단하고 프로그램 수행. 참고 : 인터프리터는 bin로 작성되었다.
6 The shell waits for your program to finish // 모든 프로그램은 종료시 return 값을 parent shell에게 반환함 
... return 값을 확인하는 방법
$ echo hi
$ echo $?
0
$ cp 
error msg
$ echo $?
1
...
7 The shell is ready for the next command


The Subprocess Environment

Parent { Shell Program Code, Local Data, Environment Data }
=> Fork, Execute
Child {New Program code, New Local Data, Environment Data }
=> Return value
Parent { Shell Program Code, Local Data, Environment Data }


반응형

'IoT 과정' 카테고리의 다른 글

Variable  (0) 2017.07.05
Shell Scripting  (0) 2017.07.05
HPUX - Managing Users and Groups  (0) 2017.06.26
HPUX - Shell Programming - Loops  (0) 2017.06.23
HPUX - Shell Programming - Branches  (0) 2017.06.23