[AIX 운영 체제와 장치 관리 21] Korn 셸 (2) — 제한 Korn 셸, 예약어, 확장 Korn 셸(ksh93), 종료 상태, 매개변수와 매개변수 치환
https://archive.horanglab.com/posts/aix-osdev-21
핵심 정리
- 제한 Korn 셸(
rksh,ksh -r)은 디렉터리 변경, SHELL·ENV·PATH 설정, 슬래시가 든 명령 경로,>·>|·<>·>>방향 바꾸기를 막습니다. - ksh93은 기본 ksh와 대체로 위 호환이며 libm 함수·부동소수점·64진법 산술, 복합 변수, 연관 배열(
typeset -A), 이름 참조(typeset -n), 부분 문자열·치환 펼치기, 규율 함수(get·set·unset)를 더합니다. - ksh93에서는
typeset -fx·alias -x로 내보낼 수 없고,$'...'이 ANSI C 문자열이며, ERRNO가 없고, PS1·PS3·ENV에도 명령 치환·산술 펼치기가 일어납니다. - 비대화식 셸에서 특수 내장 명령의 오류는 대부분 셸을 끝내지만 다른 유틸리티의 구문·방향 바꾸기·할당 오류는 끝내지 않습니다.
- 배열 첨자는 0~511,
${P:-W}·${P:=W}·${P:?W}·${P:+W}와#·##·%·%%패턴 제거를 씁니다.$$는 셸 PID,$!는 마지막 백그라운드 PID,$?는 마지막 종료 값입니다.
| 항목 | 내용 |
|---|---|
| 버전 | AIX 6.1 (5.3판과 거의 같음) |
| 원문 | Operating system and device management — 5.3판 405412쪽, 6.1판 214219쪽 |
| 관련 명령어 | rksh, ksh -r, ksh93, rksh93, typeset, set -A, hist, printf, getconf |
| 관련 파일 | /usr/bin/ksh, /usr/bin/ksh93, /usr/rbin, $HOME/.profile, /etc/environment |
제한 Korn 셸은 일반 Korn 셸보다 기능을 더 통제하는 로그인 이름과 실행 환경을 설정하는 데 씁니다.
rksh나 ksh -r 명령이 제한 Korn 셸을 엽니다. 이 명령들은 다음 동작이 허용되지 않는다는 점만 빼면 ksh 명령과 똑같이 동작합니다.
- 현재 작업 디렉터리 바꾸기
- SHELL, ENV, PATH 변수 값 설정
/(슬래시)가 든 명령 경로 이름 지정>(오른쪽 꺾쇠),>|(오른쪽 꺾쇠와 파이프 기호),<>(왼쪽·오른쪽 꺾쇠),>>(오른쪽 꺾쇠 둘)로 명령 출력의 방향 바꾸기
제한 Korn 셸은 실행할 명령이 셸 프로시저라고 판단하면 Korn 셸로 그 명령을 실행합니다. 이렇게 하면 최종 사용자에게 제한된 명령 메뉴만 주면서 Korn 셸의 모든 기능에 접근하는 셸 프로시저를 제공할 수 있습니다. 이때 사용자는 같은 디렉터리에 쓰기와 실행 권한을 함께 가지지 않는다고 가정합니다.
Korn 셸을 시작할 때 File [Parameter] 매개변수를 지정하면 셸은 File 매개변수로 지정한 스크립트 파일을 지정한 매개변수와 함께 실행합니다. 지정한 스크립트 파일에는 읽기 권한이 있어야 합니다. 스크립트 파일의 setuid와 setgid 설정은 무시됩니다. 그런 다음 셸은 명령을 읽습니다. -c나 -s 플래그를 쓰면 스크립트 파일을 지정하지 않습니다.
rksh 명령으로 시작하면 셸은 .profile과 /etc/environment 파일을 해석한 뒤 제한을 겁니다. 그래서 .profile 파일 작성자는 설정 작업을 하고 사용자를 알맞은 디렉터리(아마 로그인 디렉터리가 아닌 곳)에 두어 사용자 동작을 완전히 통제할 수 있습니다. 관리자는 /usr/rbin 디렉터리에 명령 디렉터리를 만들고 PATH 변수에 그 디렉터리를 넣어 rksh 명령이 쓰게 할 수 있습니다. ksh -r 명령으로 시작하면 셸은 .profile 파일을 해석할 때 제한을 적용합니다.
rksh 명령으로 호출하면 제한 Korn 셸은 사용자의 .profile 파일($HOME/.profile)을 읽습니다. 이 동안에는 인터럽트가 명령 수준으로 돌아가는 대신 바로 종료한다는 점만 빼면 일반 Korn 셸처럼 동작합니다.
Korn 셸이나 POSIX 셸의 예약어
다음 예약어는 Korn 셸이나 POSIX 셸에 특별한 뜻이 있습니다.
!, case, do, done, elif, else, esac, fi, for, function, if, in, select, then, time, until, while, {, }, [[, ]] (6.1판에서 빠진 목록을 5.3판에서 옮김)
예약어는 따옴표 없이 나타나고 다음 자리에 쓰일 때만 인식됩니다.
- 명령의 첫 단어
- case, for, in이 아닌 예약어 바로 뒤의 첫 단어
- case나 for 명령의 셋째 단어(이 경우 in만 유효)
확장 Korn 셸(ksh93)
AIX는 시스템 기본 Korn 셸(/usr/bin/ksh) 외에 확장판 Korn 셸 /usr/bin/ksh93을 제공합니다. 이 확장판은 현재 기본판과 대체로 위 호환되며, Korn 셸 /usr/bin/ksh에 없는 기능 몇 가지를 더 갖추고 있습니다.
두 셸은 변수 처리가 조금 다르므로 어떤 스크립트는 기본 셸과 Korn 셸 ksh93에서 다르게 동작할 수 있습니다.
참고: 확장 Korn 셸의 제한판 rksh93도 있습니다.
다음 기능은 Korn 셸 /usr/bin/ksh에는 없고 Korn 셸 /usr/bin/ksh93에는 있습니다.
산술 기능 확장 — 산술 식 안에서 $ value=$((sqrt(9)))처럼 libm 함수(보통 C 언어에서 쓰는 수학 함수)를 쓸 수 있습니다. 단항 +, ++, --, ?: 구문(예: x ? y : z), 쉼표 연산자 같은 산술 연산자를 더 쓸 수 있습니다. 진법은 64진법까지 지원합니다. 부동소수점 산술도 지원합니다. typeset -E(지수)로 산술 변수의 유효 숫자 수를, typeset -F(부동)로 소수 자릿수를 지정할 수 있습니다. SECONDS 변수는 이제 초 단위가 아니라 100분의 1초 단위까지 보여 줍니다.
복합 변수 — 복합 변수를 지원합니다. 복합 변수를 쓰면 변수 이름 하나에 값을 여러 개 지정할 수 있습니다. 각 값은 부모 변수와 마침표(.)로 구분한 하위 변수로 할당합니다. 예:
$ myvar=( x=1 y=2 )
$ print "${myvar.x}"
1
복합 할당 — 색인 배열과 연관 배열을 초기화할 때 복합 할당을 지원합니다. 할당 값은 다음 예처럼 괄호 안에 넣습니다.
$ numbers=( zero one two three )
$ print ${numbers[0]} ${numbers[3]}
zero three
연관 배열 — 연관 배열은 문자열을 색인으로 쓰는 배열입니다. ksh93에서는 typeset 명령에 -A 플래그를 써서 연관 배열을 지정합니다. 예:
$ typeset -A teammates
$ teammates=( [john]=smith [mary]=jones )
$ print ${teammates[mary]}
jones
변수 이름 참조 — typeset 명령에 -n 플래그를 쓰면 한 변수 이름을 다른 변수의 참조로 할당할 수 있습니다. 그러면 변수 값을 바꾸면 참조한 변수의 값도 바뀝니다. 예:
$ greeting="hello"
$ typeset -n welcome=greeting # establishes the reference
$ welcome="hi there" # overrides previous value
$ print $greeting
hi there
매개변수 펼치기 — 다음 매개변수 펼치기 구문을 쓸 수 있습니다.
${!varname}— 변수 자신의 이름${!varname[@]}— varname 배열의 색인 이름들${param:offset}— param의 offset부터 시작하는 부분 문자열${param:offset:num}— param의 offset부터 num 문자만큼의 부분 문자열${@:offset}— offset부터 시작하는 모든 위치 매개변수${@:offset:num}— offset부터 시작하는 위치 매개변수 num개${param/pattern/repl}— param에서 pattern의 첫 일치를 repl로 바꾼 값${param//pattern/repl}— param에서 pattern의 모든 일치를 repl로 바꾼 값${param/#pattern/repl}— param이 pattern으로 시작하면 그 부분을 repl로 바꿈${param/%pattern/repl}— param이 pattern으로 끝나면 그 부분을 repl로 바꿈
규율(discipline) 함수 — 규율 함수는 특정 변수와 연결된 함수입니다. 그 변수를 참조하거나 설정하거나 해제할 때마다 호출할 함수를 정의할 수 있습니다. 이 함수는 varname.function 꼴이며, varname은 변수 이름, function은 규율 함수입니다. 미리 정의된 규율 함수는 get, set, unset입니다.
- varname.get 함수는 varname을 참조할 때마다 호출됩니다. 이 함수 안에서 특수 변수 .sh.value를 설정하면 varname의 값이 그 값으로 바뀝니다. 간단한 예로 현재 시각이 있습니다.
$ function time.get
> {
> .sh.value=$(date +%r)
> }
$ print $time
09:15:58 AM
$ print $time # it will change in a few seconds
09:16:04 AM
- varname.set 함수는 varname을 설정할 때마다 호출됩니다. .sh.value 변수에는 할당한 값이 들어 있습니다. 함수가 끝날 때의 .sh.value 값이 varname에 할당됩니다. 예:
$ function adder.set
> {
> let .sh.value="${.sh.value} + 1"
> }
$ adder=0
$ echo $adder
1
$ adder=$adder
$ echo $adder
2
- varname.unset 함수는 varname을 해제할 때마다 실행됩니다. 함수 안에서 해제하지 않으면 변수는 실제로 해제되지 않고 값을 유지합니다.
모든 규율 함수 안에서 특수 변수 .sh.name에는 변수 이름이, .sh.subscript에는 (해당하면) 변수의 첨자 값이 설정됩니다.
함수 환경 — function myfunc 형식으로 선언한 함수는 별도 함수 환경에서 실행되며 지역 변수를 지원합니다. myfunc()로 선언한 함수는 부모 셸과 같은 환경에서 실행됩니다.
변수 — .sh.로 시작하는 변수는 셸이 예약하며 특별한 뜻이 있습니다. .sh.name, .sh.value, .sh.subscript는 규율 함수 설명을 봅니다. 셸 버전을 나타내는 .sh.version도 있습니다.
명령 반환 값 — 명령의 반환 값은 다음과 같습니다.
- 실행할 명령을 찾지 못하면 반환 값은 127입니다.
- 실행할 명령을 찾았지만 실행할 수 없으면 반환 값은 126입니다.
- 명령을 실행했지만 신호로 끝나면 반환 값은 256에 신호 번호를 더한 값입니다.
PATH 검색 규칙 — 특수 내장 명령을 먼저 찾고, 그다음 (FPATH 디렉터리의 것을 포함한) 모든 함수, 그다음 다른 내장 명령을 찾습니다.
셸 기록 — hist 명령으로 셸의 명령 기록을 보고 편집할 수 있습니다. ksh 셸에서는 fc 명령을 썼습니다. fc 명령은 hist의 별명입니다. 변수로는 셸의 현재 기록에서 명령을 실행할 때마다 1씩 느는 HISTCMD와, hist 명령에 쓸 편집기를 지정하는 HISTEDIT가 있습니다.
내장 명령 — 확장 Korn 셸에는 다음 내장 명령이 있습니다.
- builtin 명령은 쓸 수 있는 모든 내장 명령을 나열합니다.
- printf 명령은 C 라이브러리 루틴 printf()와 비슷하게 동작합니다. printf 명령을 봅니다.
- disown은 셸이 지정한 명령에 SIGHUP을 보내지 못하게 막습니다.
- getconf 명령은 독립 명령
/usr/bin/getconf와 똑같이 동작합니다. getconf 명령을 봅니다. - read 내장 명령에는 다음 플래그가 있습니다.
read -d {char}— 기본 줄 바꿈 대신 구분 문자를 지정합니다.read -t {seconds}— 초 단위 제한 시간을 지정하며, 시간이 지나면 read 명령은FALSE를 돌려줍니다.
- exec 내장 명령에는 다음 플래그가 있습니다.
exec -a {name} {cmd}— cmd의 인수 0을 name으로 바꿉니다.exec -c {cmd}— cmd를 실행하기 전에 환경을 비웁니다.
- kill 내장 명령에는 다음 플래그가 있습니다.
kill -n {signum}은 프로세스에 보낼 신호 번호를,kill -s {signame}은 신호 이름을 지정합니다.- 인수 없는
kill -l은 번호 없이 모든 신호 이름을 나열합니다.
- whence 내장 명령에는 다음 플래그가 있습니다.
-a플래그는 처음 찾은 것만이 아니라 일치하는 모든 것을 보여 줍니다.-f플래그는 함수를 찾지 않게 합니다.
- print와 echo 명령용 이스케이프 문자 시퀀스가 있습니다. Esc(Escape) 키는
\E시퀀스로 나타낼 수 있습니다. - 모든 일반 내장 명령은 지정한 명령의 구문을 보여 주는
-?플래그를 인식합니다. - getopts 내장 명령은
+기호로 시작하는 옵션을 허용하려면 optstring 앞에+가 있어야 합니다.
ksh와 ksh93의 그 밖의 차이 — 그 밖의 차이는 다음과 같습니다.
- ksh93에서는
typeset -fx내장 명령으로 함수를 내보낼 수 없습니다. - ksh93에서는
alias -x내장 명령으로 별명을 내보낼 수 없습니다. - ksh93에서는 달러 기호 뒤에 작은따옴표(
$')가 오면 ANSI C 문자열로 해석합니다. 예전(ksh) 동작을 얻으려면 달러 기호를 따옴표로 감싸야 합니다("$"'). - ksh93 내장 명령의 인수 해석 논리가 바뀌었습니다. ksh 내장 명령에서 문서화되지 않은 인수 조합은 ksh93에서 동작하지 않습니다. 예를 들어 ksh에서
typeset -4i는typeset -i4처럼 동작하지만 ksh93에서는 동작하지 않습니다. - ksh93에서는 특수 환경 변수 PS1, PS3, ENV를 펼칠 때 명령 치환과 산술 펼치기를 합니다. 그래서 예전 동작을 유지하려면 역따옴표와 달러 기호·여는 괄호(
$()를 백슬래시(\)로 이스케이프해야 합니다. 예를 들어 ksh는x=$'name\toperator'를 글자 그대로$name\toperator로 할당하지만, ksh93은\t를 펼쳐 name, 탭, operator로 할당합니다. ksh 동작을 유지하려면x="$"'name\toperator'처럼 달러 기호를 따옴표로 감싸야 합니다. - ksh93에서는 ERRNO 변수가 없어졌습니다.
- ksh93에서는 비대화식 셸에서 방향 바꾸기 기호 뒤의 파일 이름을 펼치지 않습니다.
- ksh93에서는 추적 별명을 보려면 alias 명령의
-t옵션을 써야 합니다. - ksh93의 emacs 모드에서 Ctrl+T는 현재 문자와 앞 문자를 바꿉니다. ksh에서는 현재 문자와 다음 문자를 바꿉니다.
- ksh93은
${name operator value}안에서 짝이 맞지 않는 괄호를 허용하지 않습니다. 예를 들어${name-(}는 두 버전에서 모두 동작하려면${name-\(}처럼 이스케이프해야 합니다. - ksh93에서
kill -l명령은 신호 번호 없이 신호 이름만 나열합니다.
Korn 셸이나 POSIX 셸의 종료 상태
구문 오류처럼 셸이 감지한 오류가 나면 셸은 0이 아닌 종료 상태를 돌려줍니다. 그렇지 않으면 마지막으로 실행한 명령의 종료 상태를 돌려줍니다.
셸은 실행 중 감지한 오류를 명령이나 함수 이름과 오류 조건을 출력해 보고합니다. 오류가 난 줄 번호가 1보다 크면 명령이나 함수 이름 뒤에 줄 번호도 [ ](대괄호) 안에 출력합니다.
비대화식 셸에서 특수 내장 명령이나 다른 종류의 명령이 오류를 만나면 셸은 다음 표처럼 진단 메시지를 씁니다.
| 오류 | 특수 내장 명령 | 다른 유틸리티 |
|---|---|---|
| 셸 언어 구문 오류 | 끝남 | 끝남 |
| 유틸리티 구문 오류(옵션이나 피연산자 오류) | 끝남 | 끝나지 않음 |
| 방향 바꾸기 오류 | 끝남 | 끝나지 않음 |
| 변수 할당 오류 | 끝남 | 끝나지 않음 |
| 펼치기 오류 | 끝남 | 끝남 |
| 명령을 찾지 못함 | 해당 없음 | 끝날 수 있음 |
| 점 스크립트를 찾지 못함 | 끝남 | 해당 없음 |
"끝남(끝날 수 있음)"으로 표시한 오류가 서브셸에서 나면 서브셸은 0이 아닌 상태로 끝나지만(끝날 수 있지만), 그 서브셸을 담은 스크립트는 그 오류 때문에 끝나지 않습니다.
표의 모든 경우에 대화식 셸은 끝나지 않고 표준 오류에 진단 메시지를 씁니다.
Korn 셸의 매개변수
Korn 셸 매개변수는 다음과 같습니다.
매개변수는 다음 가운데 하나로 정의됩니다.
- 별표(
*), at 기호(@), 샵 기호(#), 물음표(?), 하이픈(-), 달러 기호($), 느낌표(!) 문자 가운데 하나인 식별자. 이를 특수 매개변수라고 합니다. - 숫자로 나타낸 인수(위치 매개변수)
- 식별자로 나타내며 값과 0개 이상의 속성을 가진 매개변수(이름 있는 매개변수, 곧 변수)
typeset 특수 내장 명령은 이름 있는 매개변수에 값과 속성을 할당합니다. Korn 셸이 지원하는 속성은 typeset 특수 내장 명령에서 설명합니다. 내보낸 매개변수는 값과 속성을 환경으로 넘깁니다.
이름 있는 매개변수의 값은 다음과 같이 할당합니다.
Name=Value [ Name=Value ] ...
Name 매개변수에 -i 정수 속성이 설정돼 있으면 Value 매개변수에 산술 평가를 합니다.
셸은 1차원 배열 기능을 지원합니다. 배열 매개변수의 원소는 첨자로 참조합니다. 첨자는 대괄호 [ ]로 감싼 산술 식입니다. 배열에 값을 할당하려면 set -A Name Value ...를 씁니다. 모든 첨자 값은 0부터 511 사이여야 합니다. 배열은 선언할 필요가 없습니다. 이름 있는 매개변수를 올바른 첨자로 참조하면 언제나 올바르며 필요하면 배열이 만들어집니다. 첨자 없이 배열을 참조하면 원소 0을 참조하는 것과 같습니다.
위치 매개변수는 set 특수 명령으로 값을 할당합니다. $0 매개변수는 셸을 호출할 때 인수 0에서 설정됩니다. $ 문자는 치환할 수 있는 매개변수를 시작하는 데 씁니다.
관련 개념
- 셸 시작 — ksh 명령, psh 명령(POSIX 셸), exec 명령으로 Korn 셸을 시작할 수 있습니다.
- Korn 셸 함수 — function 예약어로 셸 함수를 정의합니다. 셸은 함수를 읽어 내부에 저장하며, 별명 이름은 함수를 읽을 때 해석합니다. 셸은 함수를 명령과 같은 방식으로 실행하며 인수는 위치 매개변수로 넘깁니다.
- Korn 셸이나 POSIX 셸의 산술 평가
관련 참조
- Korn 셸 복합 명령 — 복합 명령은 단순 명령 목록이나 파이프라인일 수도 있고 예약어로 시작할 수도 있습니다. 셸 스크립트를 쓸 때는 대개 if, while, for 같은 복합 명령을 씁니다.
Korn 셸이나 POSIX 셸의 매개변수 치환
Korn 셸(POSIX 셸)에서는 매개변수 치환을 할 수 있습니다.
치환할 수 있는 매개변수는 다음과 같습니다.
${Parameter}— 셸은${부터 짝이 맞는}까지의 모든 문자를, 그 단어에 중괄호나 메타 문자가 있더라도 같은 단어의 일부로 읽습니다. 지정한 매개변수의 값(있으면)으로 치환합니다. Parameter 뒤에 이름의 일부로 해석하면 안 되는 문자, 숫자, 밑줄이 오거나, 이름 있는 매개변수에 첨자를 붙일 때는 중괄호가 필요합니다. 지정한 매개변수가 숫자 하나 이상이면 위치 매개변수입니다. 두 자리 이상의 위치 매개변수는 중괄호로 감싸야 합니다. 변수 값이*나@이면$1부터 각 위치 매개변수로 (필드 구분 문자로 구분해) 치환합니다. 첨자가*나@인 배열 식별자를 쓰면 각 원소의 값으로 (필드 구분 문자로 구분해) 치환합니다.${#Parameter}— Parameter 값이*나@이면 위치 매개변수의 개수로 치환합니다. 아니면 Parameter 값의 길이로 치환합니다.${#Identifier[*]}— Identifier로 지정한 배열의 원소 수로 치환합니다.${Parameter:-Word}— Parameter가 설정돼 있고 비어 있지 않으면 그 값으로, 아니면 Word 값으로 치환합니다.${Parameter:=Word}— Parameter가 설정되지 않았거나 비어 있으면 Word 값으로 설정합니다. 위치 매개변수는 이 방법으로 할당할 수 없습니다.${Parameter:?Word}— Parameter가 설정돼 있고 비어 있지 않으면 그 값으로 치환합니다. 아니면 Word 값을 출력하고 셸을 끝냅니다. Word를 생략하면 표준 메시지를 출력합니다.${Parameter:+Word}— Parameter가 설정돼 있고 비어 있지 않으면 Word 값으로 치환합니다.${Parameter#Pattern},${Parameter##Pattern}— 지정한 셸 Pattern이 Parameter 값의 앞부분과 맞으면 맞은 부분을 지운 Parameter 값으로 치환합니다. 아니면 Parameter 값으로 치환합니다. 앞 형식은 가장 짧게 맞는 패턴을, 뒤 형식은 가장 길게 맞는 패턴을 지웁니다.${Parameter%Pattern},${Parameter%%Pattern}— 지정한 셸 Pattern이 Parameter 값의 끝부분과 맞으면 맞은 부분을 지운 Parameter 값으로 치환합니다. 아니면 Parameter 값으로 치환합니다. 앞 형식은 가장 짧게, 뒤 형식은 가장 길게 맞는 패턴을 지웁니다.
앞의 식에서 Word는 치환 문자열로 쓰일 때만 평가합니다. 그래서 다음 예에서 pwd 명령은 d가 설정되지 않았거나 비어 있을 때만 실행됩니다. echo ${d:-$(pwd)}
참고: 앞의 식에서 :를 생략하면 셸은 Parameter가 설정됐는지만 확인합니다.
관련 개념
- 지켜보지 않는 터미널 — 로그인한 채 내버려 둔 터미널은 모든 시스템을 위험하게 합니다. 가장 심각한 경우는 시스템 관리자가 root 권한으로 로그인한 터미널을 내버려 두는 것입니다. 사용자는 터미널을 떠날 때마다 로그아웃해야 합니다.
Korn 셸이나 POSIX 셸의 미리 정의된 특수 매개변수
Korn 셸이나 POSIX 셸은 일부 매개변수를 자동으로 설정합니다.
셸이 자동으로 설정하는 매개변수는 다음과 같습니다.
@—$1부터 위치 매개변수를 펼칩니다. 각 매개변수는 스페이스로 구분됩니다.$@를"로 감싸면 셸은 각 위치 매개변수를 별도 문자열로 봅니다. 위치 매개변수가 없으면 따옴표 없는 빈 문자열로 펼칩니다.*—$1부터 위치 매개변수를 펼칩니다. 셸은 각 매개변수를IFS값의 첫 문자로 구분합니다.$*를"로 감싸면 위치 매개변수 값들을 큰따옴표 안에 넣으며, 각 값은IFS의 첫 문자로 구분됩니다.#— 셸에 넘긴 위치 매개변수 수(십진수)로, 셸 프로시저 이름 자체는 세지 않습니다. 그래서$#는 설정된 위치 매개변수 가운데 가장 큰 번호가 됩니다. 주된 용도는 필요한 인수 개수가 있는지 확인하는 것입니다.-— 호출할 때나 set 명령으로 셸에 준 플래그입니다.?— 마지막으로 실행한 명령의 종료 값으로, 십진 문자열입니다. 대부분의 명령은 성공하면 0을 돌려줍니다. 셸 자신은 종료 값으로$?의 현재 값을 돌려줍니다.$— 이 셸의 프로세스 번호입니다. 프로세스 번호는 존재하는 모든 프로세스 사이에서 고유하므로, 최대 5자리인 이 문자열은 임시 파일의 고유한 이름을 만드는 데 자주 씁니다. 다음 예는 임시 파일 전용 디렉터리에 임시 파일을 만드는 권장 방법을 보여 줍니다.
temp=$HOME/temp/$$
ls >$temp
. . .
rm $temp
!— 가장 최근에 호출한 백그라운드 명령의 프로세스 번호입니다.0(영) — 셸이나 셸 스크립트의 이름으로 펼칩니다.
영어 원문
Restricted Korn shell
The Restricted Korn Shell is used to set up login names and execution environments whose capabilities are more controlled than those of the regular Korn shell.
The rksh or ksh -r command opens the Restricted Korn Shell. The behavior of these commands is identical to those of the ksh command, except that the following actions are not allowed:
Change the current working directory
Set the value of the SHELL, ENV, or PATH variables
Specify the pathname of a command containing a
/(slash)Redirect output of a command with
>(right caret),>|(right caret, pipe symbol),<>(left caret, right caret), or>>(two right carets).
If the Restricted Korn Shell determines that a command to be run is a shell procedure, it uses the Korn shell to run the command. In this way, it is possible to provide an end user with shell procedures that access the full power of the Korn shell while imposing a limited menu of commands. This situation assumes that the user does not have write and execute permissions in the same directory.
If the File [Parameter] parameter is specified when the Korn shell is started, the shell runs the script file identified by the File parameter, including any parameters specified. The script file specified must have read permission. Any setuid and setgid settings for script files are ignored. The shell then reads the commands. If either the -c or -s flag is used, do not specify a script file.
When started with the rksh command, the shell enforces restrictions after interpreting the .profile and /etc/environment files. Therefore, the writer of the .profile file has complete control over user actions by performing setup actions and leaving the user in an appropriate directory (probably not the login directory). An administrator can create a directory of commands in the /usr/rbin directory that the rksh command can use by changing the PATH variable to contain the directory. If it is started with the ksh -r command, the shell applies restrictions when interpreting the .profile files.
When called with the rksh command, the Restricted Korn Shell reads the user's .profile file ($HOME/.profile). It acts as the regular Korn shell while doing this, except that an interrupt causes an immediate exit instead of a return to command level.
Reserved words in the Korn shell or POSIX shell
The following reserved words have special meaning to the Korn shell or POSIX shell.
The reserved words are recognized only when they appear without quotation marks and when the word is used as the following:
First word of a command
First word following one of the reserved words other than case, for, or in
Third word in a case or for command (only in is valid in this case)
Enhanced Korn shell (ksh93)
In addition to the default system Korn shell (/usr/bin/ksh), AIX provides an enhanced version available as Korn shell /usr/bin/ksh93. This enhanced version is mostly upwardly compatible with the current default version, and includes a few additional features that are not available in Korn shell /usr/bin/ksh.
Some scripts might perform differently under Korn shell ksh93 than under the default shell because variable handling is somewhat different under the two shells.
Note: There is also a restricted version of the enhanced Korn shell available, called rksh93.
The following features are not available in Korn shell /usr/bin/ksh, but are available in Korn shell /usr/bin/ksh93:
- Arithmetic enhancements — You can use libm functions (math functions typically found in the C programming language), within arithmetic expressions, such as
$ value=$((sqrt(9))). More arithmetic operators are available, including the unary+,++,--, and the ?: construct (for example, "x ? y : z"), as well as the , (comma) operator. Arithmetic bases are supported up to base 64. Floating point arithmetic is also supported. "typeset -E" (exponential) can be used to specify the number of significant digits and "typeset -F" (float) can be used to specify the number of decimal places for an arithmetic variable. The SECONDS variable now displays to the nearest hundredth of a second, rather than to the nearest second. - Compound variables — Compound variables are supported. A compound variable allows a user to specify multiple values within a single variable name. The values are each assigned with a subscript variable, separated from the parent variable with a period (
.). For example:$ myvar=( x=1 y=2 ) $ print "${myvar.x}" 1 - Compound assignments — Compound assignments are supported when initializing arrays, both for indexed arrays and associative arrays. The assignment values are placed in parentheses, as shown in the following example:
$ numbers=( zero one two three ) $ print ${numbers[0]} ${numbers[3]} zero three - Associative arrays — An associative array is an array with a string as an index. The typeset command used with the
-Aflag allows you to specify associative arrays within ksh93. For example:$ typeset -A teammates $ teammates=( [john]=smith [mary]=jones ) $ print ${teammates[mary]} jones - Variable name references — The typeset command used with the
-nflag allows you to assign one variable name as a reference to another. In this way, modifying the value of a variable will in turn modify the value of the variable that is referenced. For example:$ greeting="hello" $ typeset -n welcome=greeting # establishes the reference $ welcome="hi there" # overrides previous value $ print $greeting hi there - Parameter expansions — The following parameter-expansion constructs are available: •
${!varname}is the name of the variable itself. •${!varname[@]}names the indexes for the varname array. •${param:offset}is a substring of param, starting at offset. •${param:offset:num}is a substring of param, starting at offset, for num number of characters. •${@:offset}indicates all positional parameters starting at offset. •${@:offset:num}indicates num positional parameters starting at offset. •${param/pattern/repl}evaluates to param, with the first occurrence of pattern replaced by repl. •${param//pattern/repl}evaluates to param, with every occurrence of pattern replaced by repl. •${param/#pattern/repl}if param begins with pattern, then param is replaced by repl. •${param/%pattern/repl}if param ends with pattern, then param is replaced by repl. - Discipline functions — A discipline function is a function that is associated with a specific variable. This allows you to define and call a function every time that variable is referenced, set, or unset. These functions take the form of varname.function, where varname is the name of the variable and function is the discipline function. The predefined discipline functions are get, set, and unset. • The varname.get function is invoked every time varname is referenced. If the special variable .sh.value is set within this function, then the value of varname is changed to this value. A simple example is the time of day:
$ function time.get > { > .sh.value=$(date +%r) > } $ print $time 09:15:58 AM $ print $time # it will change in a few seconds 09:16:04 AM• The varname.set function is invoked every time varname is set. The .sh.value variable is given the value that was assigned. The value assigned to varname is the value of .sh.value when the function completes. For example:$ function adder.set > { > let .sh.value=" $ {.sh.value} + 1" > } $ adder=0 $ echo $adder 1 $ adder=$adder $ echo $adder 2• The varname.unset function is executed every time varname is unset. The variable is not actually unset unless it is unset within the function itself; otherwise it retains its value. Within all discipline functions, the special variable .sh.name is set to the name of the variable, while .sh.subscript is set to the value of the variables subscript, if applicable. - Function environments — Functions declared with the
function myfuncformat are run in a separate function environment and support local variables. Functions declared asmyfunc()run with the same environment as the parent shell. - Variables — Variables beginning with
.sh.are reserved by the shell and have special meaning. See the description of Discipline Functions in this table for an explanation of .sh.name, .sh.value, and .sh.subscript. Also available is .sh.version, which represents the version of the shell. - Command return values — Return values of commands are as follows: • If the command to be executed is not found, the return value is set to 127. • If the command to be executed is found, but not executable, the return value is 126. • If the command is executed, but is terminated by a signal, the return value is 256 plus the signal number.
- PATH search rules — Special built-in commands are searched for first, followed by all functions (including those in FPATH directories), followed by other built-ins.
- Shell history — The hist command allows you to display and edit the shells command history. In the ksh shell, the fc command was used. The fc command is an alias to hist. Variables are HISTCMD, which increments once for each command executed in the shells current history, and HISTEDIT, which specifies which editor to use when using the hist command.
- Built-in commands — The enhanced Korn shell contains the following built-in commands: • The builtin command lists all available built-in commands. • The printf command works in a similar manner as the printf() C library routine. See the printf command. • The disown blocks the shell from sending a SIGHUP to the specified command. • The getconf command works in the same way as the stand-alone command /usr/bin/getconf. See the getconf command. • The read built-in command has the following flags: – read -d allows you to specify a character delimiter instead of the default newline. – read -t allows you to specify a time limit, in seconds, after which the read command will time out. If read times out, it will return
FALSE. • The exec built-in command has the following flags: – exec -a specifies that argument 0 of cmd be replaced with name. – exec -c tells exec to clear the environment before executing cmd. • The kill built-in command has the following flags: – kill -n is used for specifying a signal number to send to a process, while kill -s is used to specify a signal name. – kill -l, with no arguments, lists all signal names but not their numbers. • The whence built-in command has the following flags: – The-aflag displays all matches, not only the first one found. – The-fflag tells whence not to search for any functions. • An escape character sequence is used for use by the print and echo commands. The Esc (Escape) key can be represented by the sequence\E. • All regular built-in commands recognize the-?flag, which shows the syntax for the specified command. • The getopts built-in requires optstring to contain a leading+to allow options beginning with a+symbol. - Other miscellaneous differences between Korn shell ksh and Korn shell ksh93 — Other differences are: • With Korn shell ksh93, you cannot export functions using the typeset -fx built-in command. • With Korn shell ksh93, you cannot export an alias using the alias -x built-in command. • With Korn shell ksh93, a dollar sign followed by a single quote (
$’) is interpreted as an ANSI C string. You must quote the dollar sign (\"$\"’) to get the old (ksh) behavior. • Argument parsing logic for Korn shell ksh93 built-in commands has been changed. The undocumented combinations of argument parsing to Korn shell ksh built-in commands do not work in Korn shell ksh93. For example, typeset -4i works similar to typeset -i4 in Korn shell ksh, but does not work in Korn shell ksh93. • With Korn shell ksh93, command substitution and arithmetic expansion is performed on special environment variables PS1, PS3, and ENV while expanding. Therefore, you must escape the grave symbol (') and the dollar sign and opening parenthesis symbols ($() using a backslash (\) to retain the old behavior. For example, Korn shell ksh literally assigns x=$’name\toperator’as$name\toperator; Korn shell ksh93 expands\tand assigns it asname<\t expanded>operator. To preserve the Korn shell ksh behavior, you must quote$. For example,x="$"’name\toperator’. • The ERRNO variable has been removed in Korn shell ksh93. • In Korn shell ksh93, file names are not expanded for non-interactive shells after the redirection symbol. • With Korn shell ksh93, you must use the-toption of the alias command to display tracked aliases. • With Korn shell ksh93, in emacs mode, Ctrl+T swaps the current and previous character. With ksh, Ctrl+T swaps the current and next character. • Korn shell ksh93 does not allow unbalanced parentheses within${name operator value}. For example,${name-(}needs an escape such as${name-\(}to work in both versions. • With Korn shell ksh93, the kill -l command lists only the signal names, not their numerical values.
Exit status in the Korn shell or POSIX shell
Errors detected by the shell, such as syntax errors, cause the shell to return a nonzero exit status. Otherwise, the shell returns the exit status of the last command carried out.
The shell reports detected runtime errors by printing the command or function name and the error condition. If the number of the line on which an error occurred is greater than 1, then the line number is also printed in [ ] (brackets) after the command or function name.
For a noninteractive shell, an error encountered by a special built-in or other type of command will cause the shell to write a diagnostic message as shown in the following table:
| Error | Special Built-In | Other Utilities |
|---|---|---|
| Shell language syntax error | will exit | will exit |
| Utility syntax error (option or operand error) | will exit | will not exit |
| Redirection error | will exit | will not exit |
| Variable assignment error | will exit | will not exit |
| Expansion error | will exit | will exit |
| Command not found | not applicable | may exit |
| Dot script not found | will exit | not applicable |
If any of the errors shown as "will (may) exit" occur in a subshell, the subshell will (may) exit with a nonzero status, but the script containing the subshell will not exit because of the error.
In all cases shown in the table, an interactive shell will write a diagnostic message to standard error, without exiting.
Parameters in the Korn shell
Korn shell parameters are discussed below.
A parameter is defined as the following:
Identifier of any of the characters asterisk (
*), at sign (@), pound sign (#), question mark (?), hyphen (-), dollar sign ($), and exclamation point (!). These are called special parameters.Argument denoted by a number (positional parameter )
Parameter denoted by an identifier, with a value and zero or more attributes (named parameter/variables ).
The typeset special built-in command assigns values and attributes to named parameters. The attributes supported by the Korn shell are described with the typeset special built-in command. Exported parameters pass values and attributes to the environment.
The value of a named parameter is assigned by:
Name=Value [ Name=Value ] ...
If the -i integer attribute is set for the Name parameter, then the Value parameter is subject to arithmetic evaluation.
The shell supports a one-dimensional array facility. An element of an array parameter is referenced by a subscript. A subscript is denoted by an arithmetic expression enclosed by brackets [ ]. To assign values to an array, use set -A Name Value ... . The value of all subscripts must be in the range of 0 through 511. Arrays need not be declared. Any reference to a named parameter with a valid subscript is legal and an array will be created, if necessary. Referencing an array without a subscript is equivalent to referencing the element 0.
Positional parameters are assigned values with the set special command. The $0 parameter is set from argument 0 when the shell is invoked. The $ character is used to introduce parameters that can be substituted.
Related concepts
Shell startup You can start the Korn shell with the ksh command, psh command (POSIX shell), or the exec command. Korn shell functions The function reserved word defines shell functions. The shell reads and stores functions internally. Alias names are resolved when the function is read. The shell executes functions in the same manner as commands, with the arguments passed as positional parameters. Arithmetic evaluation in the Korn shell or POSIX shell The Korn shell or POSIX shell regular built-in let command enables you to perform integer arithmetic.
Related reference
Korn shell compound commands A compound command can be a list of simple commands or a pipeline, or it can begin with a reserved word. Most of the time, you will use compound commands such as if, while, and for when you are writing shell scripts.
Parameter substitution in the Korn shell or POSIX shell:
The Korn shell, or POSIX shell, lets you perform parameter substitutions.
The following are substitutable parameters:
${Parameter}— The shell reads all the characters from the${to the matching}as part of the same word, even if that word contains braces or metacharacters. The value, if any, of the specified parameter is substituted. The braces are required when the Parameter parameter is followed by a letter, digit, or underscore that is not to be interpreted as part of its name, or when a named parameter is subscripted. If the specified parameter contains one or more digits, it is a positional parameter. A positional parameter of more than one digit must be enclosed in braces. If the value of the variable is*or@), each positional parameter, starting with$1, is substituted (separated by a field separator character). If an array identifier with a subscript*or@is used, then the value for each of the elements (separated by a field separator character) is substituted.${#Parameter}— If the value of the Parameter parameter is*or@, the number of positional parameters is substituted. Otherwise, the length specified by the Parameter parameter is substituted.${#Identifier[*]}— The number of elements in the array specified by the Identifier parameter is substituted.${Parameter:-Word}— If the Parameter parameter is set and is not null, then its value is substituted; otherwise, the value of the Word parameter is substituted.${Parameter:=Word}— If the Parameter parameter is not set or is null, then it is set to the value of the Word parameter. Positional parameters cannot be assigned in this way.${Parameter:?Word}— If the Parameter parameter is set and is not null, then substitute its value. Otherwise, print the value of the Word variable and exit from the shell. If the Word variable is omitted, then a standard message is printed.${Parameter:+Word}— If the Parameter parameter is set and is not null, then substitute the value of the Word variable.${Parameter#Pattern}|${Parameter##Pattern}— If the specified shell Pattern parameter matches the beginning of the value of the Parameter parameter, then the value of this substitution is the value of the Parameter parameter with the matched portion deleted. Otherwise, the value of the Parameter parameter is substituted. In the first form, the smallest matching pattern is deleted. In the second form, the largest matching pattern is deleted.${Parameter%Pattern}|${Parameter%%Pattern}— If the specified shell Pattern matches the end of the value of the Parameter variable, then the value of this substitution is the value of the Parameter variable with the matched part deleted. Otherwise, substitute the value of the Parameter variable. In the first form, the smallest matching pattern is deleted; in the second form, the largest matching pattern is deleted. In the previous expressions, the Word variable is not evaluated unless it is to be used as the substituted string. Thus, in the following example, the pwd command is executed only if the-dflag is not set or is null:echo ${d:-$(pwd)}- Note: If the
:is omitted from the previous expressions, the shell checks only whether the Parameter
parameter is set.
Related concepts
Unattended terminals All systems are vulnerable if terminals are left logged in and unattended. The most serious problem occurs when a system manager leaves a terminal unattended that has been enabled with root authority. In general, users should log out anytime they leave their terminals.
Predefined special parameters in the Korn shell or POSIX shell:
Some parameters are set automatically by the Korn shell or POSIX shell.
The following parameters are automatically set by the shell:
@— Expands the positional parameters, beginning with$1. Each parameter is separated by a space. If you place"around$@, the shell considers each positional parameter a separate string. If no positional parameters exist, the shell expands the statement to an unquoted null string.*— Expands the positional parameters, beginning with$1. The shell separates each parameter with the first character of theIFSparameter value. If you place"around$*, the shell includes the positional parameter values in double quotation marks. Each value is separated by the first character of theIFSparameter.#— Specifies the number (in decimals) of positional parameters passed to the shell, not counting the name of the shell procedure itself. The$#parameter thus yields the number of the highest-numbered positional parameter that is set. One of the primary uses of this parameter is to check for the presence of the required number of arguments.-— Supplies flags to the shell on invocation or with the set command.?— Specifies the exit value of the last command executed. Its value is a decimal string. Most commands return 0 to indicate successful completion. The shell itself returns the current value of the$?parameter as its exit value.$— Identifies the process number of this shell. Because process numbers are unique among all existing processes, this string of up to 5 digits is often used to generate unique names for temporary files. The following example illustrates the recommended practice of creating temporary files in a directory used only for that purpose:temp=$HOME/temp/$$ ls >$temp . . . rm $temp!— Specifies the process number of the most recent background command invoked.zero (0)— Expands to the name of the shell or shell script.