[AIX 운영 체제와 장치 관리 22] Korn 셸 (3) — 파일 이름 치환, 입출력 방향 바꾸기, 코프로세스, 특수·일반 내장 명령 설명(set, typeset, trap, ulimit 등)

핵심 정리

  • 파일 이름 치환에서 *, ?, [...], [[:class:]]과 복합 패턴 ?( ), *( ), +( ), @( ), !( )를 씁니다. 점으로 시작하는 파일은 점으로 시작하는 패턴만 맞습니다.
  • 방향 바꾸기는 <, >, >|(noclobber 무시), >>, <>, <<[-](here 문서), <&n, >&n, <&-, >&-, <&p, >&p이며 순서가 중요합니다(1>File 2>&1).
  • 명령 뒤에 |&를 붙이면 코프로세스가 되고 print -p·read -p로 주고받으며, exec 5>&p처럼 번호 붙은 기술자로 옮길 수 있습니다.
  • 특수 내장 명령은 구문 오류로 셸이 끝날 수 있고 변수 할당이 명령 뒤에도 남습니다. set 옵션(-e, -u, -x, -o noclobber, -o vi 등)과 typeset 플래그(-L, -R, -Z, -i, -l, -u, -r, -x, -f)를 정리했습니다.
  • ulimit는 /etc/security/limits 기본값을 따르며 -H(하드)·-S(소프트)로 나누고, 둘 다 안 주면 둘 다 설정합니다. umask 기본은 022입니다.
항목 내용
버전 AIX 6.1 (5.3판과 같음)
원문 Operating system and device management — 5.3판 414425쪽, 6.1판 221231쪽
관련 명령어 set, typeset, trap, export, readonly, exec, print, read, ulimit, umask, whence, kill, jobs, fc
관련 파일 /etc/security/limits, /etc/suid_profile, /dev/null

Korn 셸(POSIX 셸)은 Word 변수로 지정한 각 명령 단어에서 특정 문자를 찾아 파일 이름 치환을 합니다.

명령 단어에 *, ?, [ 문자가 있고 -f 플래그가 설정되지 않았으면 셸은 그 단어를 패턴으로 봅니다. 셸은 그 단어를 패턴과 맞는 파일 이름들로 바꾸며, 현재 로케일의 정렬 순서로 정렬합니다. 패턴과 맞는 파일 이름을 찾지 못하면 단어를 바꾸지 않습니다.

셸이 파일 이름 치환에 패턴을 쓸 때 .과 / 문자는 명시적으로 맞춰야 합니다.

참고: Korn 셸은 다른 패턴 일치 상황에서는 이 문자들을 특별히 취급하지 않습니다.

패턴 일치 문자는 다음 치환을 뜻합니다.

  • * — 빈 문자열을 포함해 어떤 문자열과도 일치합니다.
  • ? — 아무 한 문자와 일치합니다.
  • [...] — 감싼 문자 가운데 하나와 일치합니다. 하이픈(-)으로 구분한 문자 쌍은 현재 로케일의 정렬 순서로 그 쌍 사이(양끝 포함)에 있는 문자와 일치합니다. 여는 [ 바로 뒤 첫 문자가 !이면 감싸지 않은 문자와 일치합니다. 하이픈(-)은 문자 집합의 처음이나 끝에 두면 집합에 넣을 수 있습니다.

대괄호 사이에 [:charclass:] 구문으로 문자 클래스 이름을 지정해 그 클래스에 정의된 모든 문자와 일치시킬 수도 있습니다. 문자 클래스 이름 몇 가지는 다음과 같습니다.

alnum, alpha, cntrl, digit, graph, lower, print, punct, space, upper, xdigit

예를 들어 [[:upper:]]는 아무 대문자와 일치합니다.

Korn 셸은 정렬 요소, 기호, 동치 클래스에 기반한 파일 이름 펼치기를 지원합니다.

PatternList는 막대(|)로 구분한 패턴 하나 이상의 목록입니다. 복합 패턴은 다음 가운데 하나 이상으로 만듭니다.

  • ?(PatternList) — 주어진 패턴 가운데 하나와 선택적으로 일치합니다.
  • *(PatternList) — 주어진 패턴이 0번 이상 나오는 것과 일치합니다.
  • +(PatternList) — 주어진 패턴이 1번 이상 나오는 것과 일치합니다.
  • @(PatternList) — 주어진 패턴 가운데 정확히 하나와 일치합니다.
  • !(PatternList) — 주어진 패턴 가운데 하나를 뺀 모든 것과 일치합니다.

패턴 일치에는 몇 가지 제약이 있습니다. 파일 이름의 첫 문자가 점(.)이면 점으로 시작하는 패턴만 그 파일과 맞습니다. 예를 들어 *는 myfile과 yourfile과는 맞지만 .myfile과 .yourfile과는 맞지 않습니다. 이런 파일과 맞추려면 다음과 같은 패턴을 씁니다.

text
.*file

패턴이 어떤 파일 이름과도 맞지 않으면 패턴 자체를 일치 결과로 돌려줍니다.

파일과 디렉터리 이름에는 *, ?, [, ] 문자를 넣지 않아야 합니다. 패턴 일치 시도 중 무한 재귀(무한 반복)를 일으킬 수 있기 때문입니다.

따옴표 제거

따옴표로 감싸지 않은 일부 문자는 지워집니다.

원래 단어에 있던 따옴표 문자, 곧 백슬래시(\), 작은따옴표('), 큰따옴표(")는 그 자신이 따옴표로 감싸지지 않았으면 지워집니다.

Korn 셸이나 POSIX 셸의 입출력 방향 바꾸기

Korn 셸은 명령을 실행하기 전에 명령행에서 방향 바꾸기 문자를 찾습니다. 이 특수 표기는 셸에 입력과 출력의 방향을 바꾸라고 지시합니다.

방향 바꾸기 문자는 단순 명령 안 어디에나 나올 수 있고, 명령 앞이나 뒤에 올 수도 있습니다. 호출한 명령에는 넘어가지 않습니다.

따로 적은 경우를 빼고 셸은 Word나 Digit 매개변수를 쓰기 전에 명령과 매개변수 치환을 합니다. 파일 이름 치환은 패턴이 파일 하나와만 맞을 때 일어나며 공백 해석은 하지 않습니다.

  • <Word — Word 매개변수로 지정한 파일을 표준 입력(파일 기술자 0)으로 씁니다.
  • >Word — Word 매개변수로 지정한 파일을 표준 출력(파일 기술자 1)으로 씁니다. 파일이 없으면 셸이 만듭니다. 파일이 있고 noclobber 옵션이 켜져 있으면 오류가 나고, 아니면 파일 길이를 0으로 자릅니다. 참고: 여러 셸에 noclobber 옵션이 설정돼 있고 같은 파일로 출력을 보내면 경쟁 조건이 생겨 둘 이상의 셸 프로세스가 파일에 쓸 수 있습니다. 셸은 이런 경쟁 조건을 감지하거나 막지 않습니다.
  • >|Word — >Word와 같지만 noclobber 옵션을 무시합니다.
  • >>Word — Word 매개변수로 지정한 파일을 표준 출력으로 씁니다. 파일이 있으면 (먼저 파일 끝을 찾아) 출력을 덧붙입니다. 파일이 없으면 셸이 만듭니다.
  • <>Word — Word 매개변수로 지정한 파일을 읽기·쓰기용으로 열어 표준 입력으로 씁니다.
  • <<[-]Word — Word 매개변수 값만 있는 줄이나 파일 끝 문자를 만날 때까지 셸 입력을 한 줄씩 읽습니다. 지정한 파일에는 매개변수 치환, 명령 치환, 파일 이름 치환을 하지 않습니다(원문 그대로. 실제 동작은 아래 설명을 따릅니다). 이렇게 만든 문서를 here 문서라고 하며 표준 입력이 됩니다. Word 매개변수의 문자가 하나라도 따옴표로 감싸져 있으면 문서의 문자를 해석하지 않습니다.

here 문서는 다음 줄 바꿈 문자 뒤에 시작해 뒤 공백 없이 구분자만 있는 줄까지 이어지는 한 단어로 취급합니다. 그런 다음 다음 here 문서가 있으면 시작합니다. 형식은 다음과 같습니다.

text
[n]<<word
   here document
delimiter

word의 문자가 하나라도 따옴표로 감싸져 있으면 word에서 따옴표를 지운 것이 구분자가 되고, here 문서의 줄은 펼치지 않습니다. 그렇지 않으면 word 자체가 구분자입니다. word에 따옴표로 감싼 문자가 없으면 here 문서의 모든 줄에 매개변수 펼치기, 명령 치환, 산술 펼치기를 합니다.

셸은 방향을 바꾼 데이터에 매개변수 치환을 합니다. 셸이 \, $, 작은따옴표(') 문자와 Word 매개변수의 첫 문자를 해석하지 않게 하려면 그 문자 앞에 \를 붙입니다.

<<에 하이픈(-)을 붙이면 셸은 Word 매개변수와 문서에서 앞쪽 탭을 모두 지웁니다.

  • <&Digit — Digit 매개변수로 지정한 파일 기술자에서 표준 입력을 복제합니다.
  • >&Digit — Digit 매개변수로 지정한 파일 기술자로 표준 출력을 복제합니다.
  • <&- — 표준 입력을 닫습니다.
  • >&- — 표준 출력을 닫습니다.
  • <&p — 코프로세스의 입력을 표준 입력으로 옮깁니다.
  • >&p — 코프로세스로 가는 출력을 표준 출력으로 옮깁니다.

이 방향 바꾸기 옵션 앞에 숫자가 오면 (기본 0이나 1 대신) 그 숫자가 가리키는 파일 기술자 번호를 씁니다. 다음 예에서 셸은 파일 기술자 2를 파일 기술자 1의 복제로 쓰기용으로 엽니다.

text
... 2>&1

방향 바꾸기를 지정하는 순서는 중요합니다. 셸은 각 방향 바꾸기를 평가할 때의 (파일 기술자, 파일) 연결로 평가합니다. 예를 들어 다음 문장에서

text
... 1>File 2>&1

파일 기술자 1은 File 매개변수로 지정한 파일과 연결됩니다. 셸은 파일 기술자 2를 파일 기술자 1과 연결된 파일(File)과 연결합니다. 방향 바꾸기 순서를 거꾸로 하면 파일 기술자 2는 (파일 기술자 1이 그전에 터미널이었다면) 터미널과 연결되고, 파일 기술자 1은 File 매개변수로 지정한 파일과 연결됩니다.

명령 뒤에 앰퍼샌드(&)가 오고 작업 제어가 활성이 아니면 명령의 기본 표준 입력은 빈 파일 /dev/null입니다. 그렇지 않으면 명령 실행 환경에는 호출한 셸의 파일 기술자를 입출력 지정에 따라 바꾼 것이 들어 있습니다.

관련 개념

  • 입출력 방향 바꾸기

관련 작업

  • 인라인 입력(here) 문서로 출력 방향 바꾸기

코프로세스 기능

Korn 셸(POSIX 셸)에서는 명령 하나 이상을 백그라운드 프로세스로 실행할 수 있습니다. 셸 스크립트 안에서 실행하는 이런 명령을 코프로세스라고 합니다.

명령 뒤에 |& 연산자를 붙여 코프로세스로 지정합니다. 명령의 표준 입력과 출력 모두 스크립트에 파이프로 연결됩니다.

코프로세스는 다음 제약을 지켜야 합니다.

  • 각 메시지 끝에 줄 바꿈 문자를 넣습니다.
  • 각 출력 메시지를 표준 출력으로 보냅니다.
  • 각 메시지 뒤에 표준 출력을 비웁니다(flush).

다음 예는 코프로세스에 입력을 넘기고 돌려받는 방법을 보여 줍니다.

text
echo "Initial process"
./FileB.sh |&
read -p a b c d
echo "Read from coprocess: $a $b $c $d"
print -p "Passed to the coprocess"
read -p a b c d
echo "Passed back from coprocess: $a $b $c $d"
FileB.sh
   echo "The coprocess is running"
   read a b c d
   echo $a $b $c $d

결과 표준 출력은 다음과 같습니다.

text
Initial process
Read from coprocess: The coprocess is running
Passed back from coprocess: Passed to the coprocess

코프로세스에 쓰려면 print -p 명령을, 코프로세스에서 읽으려면 read -p 명령을 씁니다.

관련 개념

  • Korn 셸 또는 POSIX 셸 명령

코프로세스 입출력의 방향 바꾸기

입출력 방향 바꾸기로 코프로세스의 표준 입력과 출력을 번호 붙은 파일 기술자로 다시 지정합니다.

예를 들어 다음 명령은

text
exec 5>&p

코프로세스의 입력을 파일 기술자 5로 옮깁니다.

이렇게 한 뒤에는 표준 방향 바꾸기 구문으로 명령 출력을 코프로세스로 보낼 수 있습니다. 다른 코프로세스를 시작할 수도 있습니다. 두 코프로세스의 출력은 같은 파이프에 연결되며 read -p 명령으로 읽습니다. 코프로세스를 멈추려면 다음을 입력합니다.

text
read -u5

Korn 셸이나 POSIX 셸 내장 명령

특수 명령은 Korn 셸과 POSIX 셸에 내장돼 셸 프로세스 안에서 실행됩니다.

따로 적지 않으면 출력은 파일 기술자 1에 쓰고, 명령에 구문 오류가 없으면 종료 상태는 0입니다. 입출력 방향 바꾸기를 쓸 수 있습니다. 내장 명령에는 특수 내장 명령과 일반 내장 명령 두 종류가 있습니다.

특수 내장 명령은 다음 점에서 일반 내장 명령과 다릅니다.

  • 특수 내장 명령의 구문 오류는 명령을 실행하는 셸을 끝낼 수 있습니다. 일반 내장 명령의 구문 오류로는 그렇지 않습니다. 특수 내장 명령의 구문 오류가 셸을 끝내지 않으면 종료 값은 0이 아닙니다.
  • 특수 내장 명령으로 지정한 변수 할당은 명령이 끝난 뒤에도 유효합니다.
  • 입출력 방향 바꾸기는 매개변수 할당 뒤에 처리합니다.

또 export, readonly, typeset 특수 명령 뒤의 매개변수 할당 꼴 단어는 매개변수 할당과 같은 규칙으로 펼칩니다. = 뒤에 틸드 치환을 하고, 단어 분리와 파일 이름 치환은 하지 않습니다.

관련 개념

  • Korn 셸 또는 POSIX 셸 명령, Korn 셸 함수

관련 참조

  • Korn 셸이나 POSIX 셸의 특수 내장 명령 목록, 일반 내장 명령

Korn 셸이나 POSIX 셸의 특수 내장 명령 설명

특수 명령은 Korn 셸과 POSIX 셸에 내장돼 셸 프로세스 안에서 실행됩니다.

Korn 셸의 특수 내장 명령은 다음과 같습니다.

:, eval, newgrp, shift, ., exec, readonly, times, break, exit, return, trap, continue, export, set, typeset, unset

  • : [Argument ...] — 인수를 펼치기만 합니다. if 명령의 then 조건처럼 명령이 필요하지만 아무것도 하지 않아야 할 때 씁니다.
  • . File [Argument ...] — 지정한 파일 전체를 읽고 그 명령을 실행합니다. 명령은 현재 셸 환경에서 실행됩니다. PATH 변수의 검색 경로로 지정한 파일이 든 디렉터리를 찾습니다. 인수를 지정하면 위치 매개변수가 되고, 아니면 위치 매개변수는 바뀌지 않습니다. 종료 상태는 가장 최근에 실행한 명령의 종료 상태입니다. 위치 매개변수는 매개변수 치환 절을 봅니다. 참고: 이 명령은 명령을 실행하기 전에 파일 전체를 읽습니다. 그래서 파일 안의 alias와 unalias 명령은 파일에서 정의한 함수에는 적용되지 않습니다.
  • break [n] — 둘러싼 for, while, until, select 반복이 있으면 빠져나갑니다. n을 지정하면 n단계를 빠져나갑니다. n은 1 이상의 정수입니다.
  • continue [n] — 둘러싼 for, while, until, select 반복의 다음 반복으로 넘어갑니다. n을 지정하면 n번째 둘러싼 반복에서 이어갑니다. n은 1 이상의 정수입니다.
  • eval [Argument ...] — 지정한 인수를 셸 입력으로 읽고 결과 명령을 실행합니다.
  • exec [Argument ...] — (새 프로세스를 만들지 않고) 이 셸 대신 인수로 지정한 명령을 실행합니다. 입출력 인수가 나와 현재 프로세스에 영향을 줄 수 있습니다. 인수를 지정하지 않으면 exec 명령은 입출력 방향 바꾸기 목록대로 파일 기술자를 바꿉니다. 이때 이 방법으로 연 2보다 큰 파일 기술자 번호는 다른 프로그램을 호출할 때 닫힙니다.
  • exit [n] — n으로 지정한 종료 상태로 셸을 끝냅니다. n은 0~255 범위의 부호 없는 십진 정수여야 합니다. n을 생략하면 종료 상태는 가장 최근에 실행한 명령의 것입니다. set 특수 명령의 ignoreeof 옵션이 켜져 있지 않으면 파일 끝 문자로도 셸이 끝납니다.
  • export -p [Name[=Value]] ... — 지정한 이름을 이후 실행하는 명령의 환경으로 자동으로 내보내도록 표시합니다. -p는 내보낸 모든 변수의 이름과 값을 "export %s=%s\n", name, value 형식으로 표준 출력에 씁니다.
  • newgrp [Group] — exec /usr/bin/newgrp [Group] 명령과 같습니다. 참고: 이 명령은 돌아오지 않습니다.
  • readonly -p [Name[=Value]] ... — Name으로 지정한 이름을 읽기 전용으로 표시합니다. 이 이름은 이후 할당으로 바꿀 수 없습니다. -p는 (원문 그대로) 내보낸 모든 변수의 이름과 값을 다음 형식으로 표준 출력에 씁니다.
text
"export %s= %s\n", <name> <value>
  • return [n] — 셸 함수가 호출한 스크립트로 돌아가게 합니다. 반환 상태는 n으로 지정합니다. n을 생략하면 가장 최근에 실행한 명령의 상태입니다. 함수나 스크립트 밖에서 return 명령을 호출하면 exit 명령과 같습니다.

  • set [+|-abCefhkmnostuvx] [+|-o Option]... [+|-A Name] [Argument ...] — 옵션이나 인수를 지정하지 않으면 모든 셸 변수의 이름과 값을 현재 로케일의 정렬 순서로 씁니다. 옵션을 지정하면 다음과 같이 셸 속성을 설정하거나 해제합니다.

    • -A — 배열 할당. Name 매개변수를 해제하고 지정한 Argument 목록에서 값을 차례로 할당합니다. +A를 쓰면 Name을 먼저 해제하지 않습니다.
    • -a — 이후 정의하는 모든 매개변수를 자동으로 내보냅니다.
    • -b — 백그라운드 작업이 끝나면 사용자에게 비동기로 알립니다.
    • -C — set -o noclobber와 같습니다.
    • -e — 명령의 종료 상태가 0이 아니면 ERR trap(설정돼 있으면)을 실행하고 끝냅니다. 단, 단순 명령이 &&나 || 목록 안에 있거나, if·while·until 바로 뒤의 명령이거나, ! 뒤 파이프라인 안에 있으면 예외입니다. 프로파일을 읽는 동안에는 꺼집니다.
    • -f — 파일 이름 치환을 끕니다.
    • -h — 각 명령을 처음 만날 때 추적 별명으로 지정합니다.
    • -k — 명령 이름 앞의 인수뿐 아니라 모든 매개변수 할당 인수를 명령의 환경에 넣습니다.
    • -m — 백그라운드 작업을 별도 프로세스로 실행하고 끝나면 한 줄을 출력합니다. 백그라운드 작업의 종료 상태는 완료 메시지로 알립니다. 작업 제어가 있는 시스템에서는 대화식 셸에서 자동으로 켜집니다. 작업 제어 절을 봅니다.
    • -n — 명령을 읽고 구문 오류를 확인하지만 실행하지 않습니다. 대화식 셸에서는 무시됩니다.
    • -o Option — 인수를 지정하지 않으면 현재 옵션 설정과 오류 메시지를 출력합니다. ksh 명령행 하나에서 여러 옵션을 설정할 수 있습니다. +o를 쓰면 지정한 옵션을 해제합니다. Option은 다음 가운데 하나입니다. allexport(-a와 같음), bgnice(모든 백그라운드 작업을 낮은 우선순위로 실행, 기본), emacs(emacs 방식 인라인 편집기), errexit(-e와 같음), gmacs(gmacs 방식 인라인 편집기), ignoreeof(파일 끝 문자로 셸을 끝내지 않음. exit 명령을 쓰거나 Ctrl-D를 11번 넘게 눌러야 끝남), keyword(-k와 같음. Bourne 셸 하위 호환용이며 쓰지 않는 것이 좋음), markdirs(파일 이름 치환 결과인 디렉터리 이름 뒤에 /를 붙임. 원문은 백슬래시라고 적음), monitor(-m과 같음), noclobber(방향 바꾸기로 기존 파일을 자르지 않음. 자르려면 >|를 씀), noexec(-n과 같음), noglob(-f와 같음), nolog(.profile과 $ENV 파일의 함수 정의를 기록 파일에 저장하지 않음), nounset(-u와 같음), privileged(-p와 같음), trackall(-h와 같음), verbose(-v와 같음), vi(vi 방식 인라인 편집기의 입력 모드로 들어감. 이스케이프 문자 033을 입력하면 이동 모드, Return은 줄을 보냄), viraw(vi 모드에서 문자를 입력하는 대로 처리), xtrace(-x와 같음).
    • -p — $HOME/.profile 파일 처리를 끄고 ENV 파일 대신 /etc/suid_profile 파일을 씁니다. 유효 UID나 GID가 실제 UID나 GID와 다르면 켜집니다. 끄면 유효 UID·GID를 실제 UID·GID로 설정합니다. 참고: 운영 체제가 setuid 셸 스크립트를 지원하지 않으므로 시스템은 -p 옵션을 지원하지 않습니다.
    • -s — 위치 매개변수를 사전순으로 정렬합니다.
    • -t — 명령 하나를 읽고 실행한 뒤 끝냅니다. Bourne 셸 하위 호환용이며 쓰지 않는 것이 좋습니다.
    • -u — 치환할 때 설정되지 않은 매개변수를 오류로 취급합니다.
    • -v — 셸 입력 줄을 읽는 대로 출력합니다.
    • -x — 명령과 인수를 실행하는 대로 출력합니다.
    • - — -x와 -v 플래그를 끄고 더 이상 인수에서 플래그를 찾지 않습니다.
    • -- — 어떤 플래그도 바꾸지 않습니다. $1을 -로 시작하는 값으로 설정할 때 쓸모 있습니다. 이 플래그 뒤에 인수가 없으면 위치 매개변수를 설정하지 않습니다.

    set 명령의 플래그 앞에 - 대신 +를 붙이면 그 플래그를 끕니다. 셸을 호출할 때도 이 플래그를 쓸 수 있습니다. 인수 없이 set +o를 호출하면 같은 옵션 설정을 이루는 셸 명령으로 다시 입력할 수 있는 형식으로 현재 옵션 설정을 보여 줍니다. 현재 플래그는 $- 매개변수에 있습니다. -A 플래그를 지정하지 않으면 나머지 인수는 위치 매개변수로 $1, $2, ... 순서로 할당됩니다. 인수가 없으면 모든 이름 있는 매개변수의 이름과 값을 표준 출력에 출력합니다.

  • shift [n] — 위치 매개변수의 번호를 $n+1부터 $1로 다시 매깁니다. n의 기본값은 1입니다. n은 0 이상 $# 이하로 평가되는 산술 식입니다.

  • times — 셸과 셸에서 실행한 프로세스의 누적 사용자·시스템 시간을 출력합니다.

  • trap [Command] [Signal] ... — 셸이 지정한 신호를 받으면 지정한 명령을 실행합니다. Command는 trap을 설정할 때 한 번, trap이 걸릴 때 한 번 읽습니다. Signal은 번호나 신호 이름으로 줄 수 있습니다. trap 명령은 신호 번호 순서로 실행됩니다. 현재 셸에 들어올 때 무시된 신호에 trap을 설정하려는 시도는 효과가 없습니다. 명령이 -이면 모든 trap을 원래 값으로 되돌립니다. 명령을 생략하고 첫 신호가 숫자이면 ksh 명령은 Signal을 원래 값으로 되돌립니다. 참고: 명령을 생략하고 첫 신호가 기호 이름이면 신호를 명령으로 해석합니다. Signal이 ERR이면 명령의 종료 상태가 0이 아닐 때마다 지정한 명령을 실행합니다. DEBUG이면 각 명령 뒤에 실행합니다. Signal이 0이나 EXIT이고 trap 명령을 함수 본문 안에서 실행하면 함수가 끝난 뒤 실행합니다. 함수 밖에서 설정한 0이나 EXIT trap은 셸이 끝날 때 실행합니다. 참고: 스크립트가 함수 안에서 SIGINT 신호를 받으면 셸이 끝날 때 EXIT 신호를 잡을 수 없습니다. 인수 없는 trap 명령은 신호 번호마다 연결된 명령 목록을 출력합니다. 지정한 명령이 NULL(빈 따옴표 "")이면 ksh 명령은 그 신호를 무시합니다. 문자 따옴표는 Korn 셸 따옴표 절을, SIG 접두사 없는 Signal 값 전체 목록은 Technical Reference의 sigaction, sigvec, signal 서브루틴을 봅니다.

  • typeset [+|-HLRZfilrtux [n]] [Name[=Value]] ... — 셸 매개변수의 속성과 값을 설정합니다. 함수 안에서 호출하면 Name 매개변수의 새 인스턴스를 만들며, 함수가 끝나면 값과 형을 되돌립니다. 다음 플래그를 쓸 수 있습니다.

    • -H — AIX가 아닌 기계에서 AIX-호스트 파일 대응을 제공합니다.
    • -L — 왼쪽 정렬하고 Value의 앞 공백을 지웁니다. n이 0이 아니면 필드 너비를 정하고, 아니면 첫 할당 값의 너비로 정합니다. 할당하면 필드에 맞게 오른쪽을 공백으로 채우거나 자릅니다. -Z도 설정돼 있으면 앞 0을 지웁니다. -R은 꺼집니다.
    • -R — 오른쪽 정렬하고 앞을 공백으로 채웁니다. n이 0이 아니면 필드 너비를 정하고, 아니면 첫 할당 값의 너비로 정합니다. 다시 할당하면 공백으로 채우거나 끝에서 자릅니다. L 플래그는 꺼집니다.
    • -Z — 첫 공백 아닌 문자가 숫자이고 -L이 설정되지 않았으면 오른쪽 정렬하고 앞을 0으로 채웁니다. n이 0이 아니면 필드 너비를 정하고, 아니면 첫 할당 값의 너비로 정합니다.
    • -f — 이름이 매개변수가 아니라 함수 이름임을 나타냅니다. 할당은 할 수 없고 다른 유효 플래그는 -t, -u, -x뿐입니다. -t는 이 함수의 실행 추적을 켭니다. -u는 함수를 미정의로 표시하며, 함수를 참조하면 FPATH 변수에서 정의를 찾습니다. -x는 ksh 명령을 따로 호출하지 않는 셸 스크립트 사이에서 함수 정의를 유지합니다.
    • -i — 매개변수를 정수로 지정해 산술을 빠르게 합니다. n이 0이 아니면 출력 진법을 정하고, 아니면 첫 할당이 출력 진법을 정합니다.
    • -l — 모든 대문자를 소문자로 바꿉니다. -u 대문자 변환 플래그는 꺼집니다.
    • -r — Name으로 지정한 이름을 읽기 전용으로 표시합니다. 이후 할당으로 바꿀 수 없습니다.
    • -t — 이름 있는 매개변수에 태그를 붙입니다. 태그는 사용자가 정의하며 셸에는 특별한 뜻이 없습니다.
    • -u — 모든 소문자를 대문자로 바꿉니다. -l 소문자 플래그는 꺼집니다.
    • -x — Name으로 지정한 이름을 이후 실행하는 명령의 환경으로 자동으로 내보내도록 표시합니다.

    - 대신 +를 쓰면 typeset 명령 플래그를 끕니다. Name 없이 플래그만 지정하면 그 플래그가 설정된 매개변수의 이름(과 선택적으로 값) 목록을 출력합니다(+를 쓰면 값을 출력하지 않습니다). 이름도 플래그도 지정하지 않으면 모든 매개변수의 이름과 속성을 출력합니다.

  • unset [-fv] Name ... — 이름 목록으로 준 매개변수의 값과 속성을 해제합니다. -v를 지정하면 Name은 변수 이름이며 셸은 변수를 해제하고 환경에서 지웁니다. 읽기 전용 변수는 해제할 수 없습니다. ERRNO, LINENO, MAILCHECK, OPTARG, OPTIND, RANDOM, SECONDS, TMOUT, 밑줄(_) 변수를 해제하면 나중에 다시 할당해도 특별한 뜻이 사라집니다. -f 플래그를 설정하면 Name은 함수 이름이며 셸은 함수 정의를 해제합니다.

Korn 셸이나 POSIX 셸의 일반 내장 명령 설명

Korn 셸과 POSIX 셸의 내장 명령은 다음과 같습니다.

Korn 셸은 다음 일반 내장 명령을 제공합니다.

alias, fg, print, ulimit, bg, getopts, pwd, umask, cd, jobs, read, unalias, command, kill, setgroups, wait, echo, let, setsenv, test, whence, fc

  • alias [-t] [-x] [AliasName[=String]] ... — 별명 정의를 만들거나 다시 정의하거나, 기존 별명 정의를 표준 출력에 씁니다. 자세한 내용은 alias 명령을 봅니다.
  • bg [JobID...] — 지정한 각 작업을 백그라운드로 보냅니다. JobID를 지정하지 않으면 현재 작업을 백그라운드로 보냅니다. 작업 제어는 작업 제어 절과 bg 명령을 봅니다.
  • cd [Argument], cd Old New — 이 명령은 두 형식 가운데 하나입니다. 첫 형식은 현재 디렉터리를 Argument로 지정한 디렉터리로 바꿉니다. Argument가 하이픈(-)이면 이전 디렉터리로 바꿉니다. HOME 셸 변수가 Argument의 기본값입니다. PWD 변수는 현재 디렉터리로 설정됩니다. CDPATH 셸 변수는 Argument 값이 든 디렉터리의 검색 경로를 정합니다. 다른 디렉터리 이름은 콜론(:)으로 구분합니다. 기본 경로는 빈 값으로 현재 디렉터리를 뜻합니다. 현재 디렉터리는 빈 경로 이름으로 나타내며, 경로 목록에서 등호 바로 뒤나 콜론 구분자 사이 어디에든 나옵니다. 지정한 인수가 슬래시(/)로 시작하면 검색 경로를 쓰지 않고, 아니면 경로의 각 디렉터리에서 인수를 찾습니다. 둘째 형식은 현재 디렉터리 이름 PWD에서 Old 문자열을 New 문자열로 바꾸고 그 새 디렉터리로 바꾸려고 합니다.
  • command [-p] CommandName [Argument ...], command [-v | -V] CommandName — 셸 함수 찾기를 하지 않고 지정한 명령과 인수를 단순 명령으로 취급하게 합니다. 자세한 내용은 command 명령을 봅니다.
  • echo [String ...] — 문자열을 표준 출력에 씁니다. 사용법은 echo 명령을 봅니다. -n 플래그는 지원하지 않습니다.
  • fc [-r] [-e Editor] [First [Last]], fc -l [-n] [-r] [First [Last]], fc -s [Old=New] [First] — 명령 기록 파일의 내용을 보여 주거나, 편집기를 호출해 셸에서 이전에 입력한 명령을 고쳐 다시 실행합니다. 자세한 내용은 fc 명령을 봅니다.
  • fg [JobID] — 지정한 각 작업을 포그라운드로 가져옵니다. 작업을 지정하지 않으면 현재 작업을 포그라운드로 가져옵니다. 자세한 내용은 fg 명령을 봅니다.
  • getopts OptionString Name [Argument ...] — Argument에서 올바른 옵션을 확인합니다. 자세한 내용은 getopts 명령을 봅니다.
  • jobs [-l | -n | -p] [JobID ...] — 현재 셸 환경에서 시작한 작업의 상태를 보여 줍니다. JobID로 특정 작업을 지정하지 않으면 모든 활성 작업의 상태를 보여 줍니다. 작업 종료를 보고하면 셸은 현재 셸 환경이 아는 목록에서 그 작업의 프로세스 ID를 지웁니다. 자세한 내용은 jobs 명령을 봅니다.
  • kill [-s {SignalName | SignalNumber}] ProcessID..., kill [-SignalName | -SignalNumber] ProcessID..., kill -l [ExitStatus] — 실행 중인 프로세스에 신호(기본은 SIGTERM)를 보냅니다. 이 기본 동작은 보통 프로세스를 멈춥니다. 프로세스를 멈추려면 ProcessID에 프로세스 ID(PID)를 지정합니다. 셸은 백그라운드에서 실행 중인 각 프로세스의 PID를 알려 줍니다(파이프라인으로 프로세스를 여럿 시작하면 마지막 프로세스 번호를 알려 줍니다). ps 명령으로도 명령의 프로세스 ID 번호를 찾을 수 있습니다. kill -l은 신호 이름을 나열합니다. 자세한 내용은 kill 명령을 봅니다.
  • let Expression ... — 지정한 산술 식을 평가합니다. 마지막 식의 값이 0이 아니면 종료 상태는 0, 아니면 1입니다. 산술 평가 절을 봅니다.
  • print [-Rnprsu [n]] [Argument ...] — 셸 출력을 출력합니다. 플래그를 지정하지 않거나 하이픈(-)이나 이중 하이픈(--) 플래그를 지정하면 인수를 echo 명령의 설명대로 표준 출력에 출력합니다. 플래그는 다음과 같습니다.
    • -R — 원시 모드로 출력합니다(echo 명령의 이스케이프 규칙 무시). -n을 뺀 이후의 모든 인수와 플래그를 출력합니다.
    • -n — 출력에 줄 바꿈 문자를 더하지 않습니다.
    • -p — 인수를 표준 출력 대신 |&로 실행한 프로세스의 파이프에 씁니다.
    • -r — 원시 모드로 출력합니다. echo 명령의 이스케이프 규칙을 무시합니다.
    • -s — 인수를 표준 출력 대신 기록 파일에 씁니다.
    • -u — 출력을 놓을 한 자리 파일 기술자 번호 n을 지정합니다. 기본값은 1입니다.
  • pwd — print -r - $PWD와 같습니다. 참고: Korn 셸 내부 pwd 명령은 심볼릭 링크를 지원하지 않습니다.
  • read [-prsu [n]] [Name?Prompt] [Name...] — 셸 입력을 받습니다. 한 줄을 읽어 IFS 변수의 문자를 구분자로 필드로 나눕니다. 자세한 내용은 read 명령을 봅니다.
  • setgroups — 별도 셸로 실행되는 /usr/bin/setgroups 명령을 실행합니다. 이 명령의 정보는 setgroups 명령을 봅니다. 다만 차이가 하나 있습니다. setgroups 내장 명령은 서브셸을 호출하지만 setgroups 명령은 현재 실행 중인 셸을 대신합니다. 내장 명령은 호환성 때문에만 지원하므로 스크립트에서는 셸 내장 명령 대신 절대 경로 /usr/bin/setgroups를 쓰는 것이 좋습니다.
  • setsenv — 현재 실행 중인 셸을 대신하는 /usr/bin/setsenv 명령을 실행합니다. setsenv 명령을 봅니다.
  • test — [ expression ]과 같습니다. 사용법은 Korn 셸 조건식 절을 봅니다.
  • ulimit [-HSacdfmst] [Limit] — /etc/security/limits 파일에 정의한 사용자 프로세스 자원 한도를 설정하거나 보여 줍니다. 이 파일에는 다음 기본 한도가 들어 있습니다.
text
fsize = 2097151
core = 2048
cpu = 3600
data = 131072
rss = 65536
stack = 8192
threads = -1

이 값은 사용자를 시스템에 더할 때 기본 설정으로 씁니다. 사용자를 더할 때 mkuser 명령으로 설정하고 chuser 명령으로 바꿉니다.

한도는 소프트와 하드로 나뉩니다. 사용자는 ulimit 명령으로 소프트 한도를 하드 한도까지 바꿀 수 있습니다. 하드 한도를 바꾸려면 root 사용자 권한이 있어야 합니다.

많은 시스템에는 이 한도 가운데 일부가 없습니다. Limit 매개변수를 지정하면 지정한 자원의 한도를 설정합니다. Limit 값은 각 자원에 지정된 단위의 수나 unlimited입니다. ulimit 명령 플래그는 다음과 같습니다.

  • -H — 주어진 자원의 하드 한도를 설정합니다. root 사용자 권한이 있으면 하드 한도를 올릴 수 있습니다. 어떤 사용자든 내릴 수는 있습니다.
  • -S — 주어진 자원의 소프트 한도를 설정합니다. 소프트 한도는 하드 한도 값까지 올릴 수 있습니다. -H도 -S도 지정하지 않으면 둘 다에 적용합니다.
  • -a — 현재 자원 한도를 모두 나열합니다.
  • -c — 코어 덤프 크기의 512바이트 블록 수를 지정합니다.
  • -d — 데이터 영역의 크기(KB)를 지정합니다.
  • -f — 자식 프로세스가 쓰는 파일의 512바이트 블록 수를 지정합니다(어떤 크기의 파일이든 읽을 수는 있음).
  • -m — 물리 메모리 크기(KB)를 지정합니다.
  • -n — 프로세스가 열 수 있는 파일 기술자 수의 한도를 지정합니다.
  • -r — 프로세스당 스레드 수의 한도를 지정합니다.
  • -s — 스택 영역의 크기(KB)를 지정합니다.
  • -t — 각 프로세스가 쓸 초 수를 지정합니다.

Limit를 생략하면 현재 자원 한도를 출력합니다. -H를 지정하지 않으면 소프트 한도를 출력합니다. 자원을 여럿 지정하면 값 앞에 한도 이름과 단위를 출력합니다. 옵션을 주지 않으면 -f로 봅니다. 값을 바꿀 때 -H나 -S를 지정하지 않으면 하드와 소프트 한도를 모두 Limit로 설정합니다.

사용자와 시스템 자원 한도에 관한 자세한 내용은 getrlimit, setrlimit, vlimit 서브루틴을 봅니다.

  • umask [-S] [Mask] — 파일 권한을 정합니다. 이 값은 만드는 프로세스의 권한과 함께 파일을 만들 때 파일 권한을 정합니다. 기본값은 022입니다. Mask를 지정하지 않으면 현재 셸 환경의 파일 모드 생성 마스크를 표준 출력에 보여 줍니다. 자세한 내용은 umask 명령을 봅니다.
  • unalias {-a | AliasName...} — 지정한 각 별명 이름의 정의를 지우거나, -a 플래그를 쓰면 모든 별명 정의를 지웁니다. 별명 정의는 현재 셸 환경에서 지워집니다. 자세한 내용은 unalias 명령을 봅니다.
  • wait [ProcessID...] — 지정한 작업을 기다리고 종료합니다. 작업을 지정하지 않으면 현재 활성인 모든 자식 프로세스를 기다립니다. 이 명령의 종료 상태는 기다린 프로세스의 것입니다. 자세한 내용은 wait 명령을 봅니다.
  • whence [-pv] Name ... — 지정한 각 이름을 명령 이름으로 쓰면 어떻게 해석될지 알려 줍니다. 플래그 없이 쓰면 각 이름에 해당하는 절대 경로 이름(있으면)을 보여 줍니다. -p는 별명, 함수, 예약어라도 지정한 이름의 경로를 찾습니다. -v는 각 이름의 종류를 지정하는 더 자세한 보고서를 만듭니다.
영어 원문

File name substitution in the Korn shell or POSIX shell

The Korn shell, or POSIX shell, performs file name substitution by scanning each command word specified by the Word variable for certain characters.

If a command word includes the *), ? or [ characters, and the -f flag has not been set, the shell regards the word as a pattern. The shell replaces the word with file names, sorted according to the collating sequence in effect in the current locale, that match that pattern. If the shell does not find a file name to match the pattern, it does not change the word.

When the shell uses a pattern for file name substitution, the . and / characters must be matched explicitly.

Note: The Korn shell does not treat these characters specially in other instances of pattern matching.

These pattern-matching characters indicate the following substitutions:

  • * — Matches any string, including the null string.
  • ? — Matches any single character.
  • [...] — Matches any one of the enclosed characters. A pair of characters separated by a hyphen (-) matches any character lexically within the inclusive range of that pair, according to the collating sequence in effect in the current locale. If the first character following the opening [ is !, then any character not enclosed is matched. A hyphen (-) can be included in the character set by putting it as the first or last character.

You can also use the [:charclass:] notation to match file names within a range indication. This format instructs the system to match any single character belonging to class. The definition of which characters constitute a specific character class is present through the LC_CTYPE category of the setlocale subroutine. All character classes specified in the current locale are recognized.

The names of some of the character classes are as follows:

  • alnum

  • alpha

  • cntrl

  • digit

  • graph

  • lower

  • print

  • punct

  • space

  • upper

  • xdigit

For example, [[:upper:]] matches any uppercase letter.

The Korn shell supports file name expansion based on collating elements, symbols, or equivalence classes.

A PatternList is a list of one or more patterns separated from each other with a |. Composite patterns are formed with one or more of the following:

  • ?(PatternList) — Optionally matches any one of the given patterns
  • *(PatternList) — Matches zero or more occurrences of the given patterns
  • +(PatternList) — Matches one or more occurrences of the given patterns
  • @(PatternList) — Matches exactly one of the given patterns
  • !(PatternList) — Matches anything, except one of the given patterns

Pattern matching has some restrictions. If the first character of a file name is a dot (.), it can be matched only by a pattern that also begins with a dot. For example, * matches the file names myfile and yourfile but not the file names .myfile and .yourfile. To match these files, use a pattern such as the following:

text
.*file

If a pattern does not match any file names, then the pattern itself is returned as the result of the attempted match.

File and directory names should not contain the characters *, ?, [, or ] because they can cause infinite recursion (that is, infinite loops) during pattern-matching attempts.

Quote removal:

Some characters will be removed if they are not quoted.

The quote characters, backslash (\), single quote (’), and double quote (") that were present in the original word will be removed unless they have themselves been quoted.

Input and output redirection in the Korn shell or POSIX shell:

Before the Korn shell executes a command, it scans the command line for redirection characters. These special notations direct the shell to redirect input and output.

Redirection characters can appear anywhere in a simple command or can precede or follow a command. They are not passed on to the invoked command.

The shell performs command and parameter substitution before using the Word or Digit parameter except as noted. File name substitution occurs only if the pattern matches a single file and blank interpretation is not performed.

  • <Word — Uses the file specified by the Word parameter as standard input (file descriptor 0).
  • >Word — Uses the file specified by the Word parameter as standard output (file descriptor 1). If the file does not exist, the shell creates it. If the file exists and the noclobber option is on, an error results; otherwise, the file is truncated to zero length. Note: When multiple shells have the noclobber option set and they redirect output to the same file, there could be a race condition, which might result in more than one of these shell processes writing to the file. The shell does not detect or prevent such race conditions.
  • >|Word — Same as the >Word command, except that this redirection statement overrides the noclobber option.
  • > >Word — Uses the file specified by the Word parameter as standard output. If the file currently exists, the shell appends the output to it (by first seeking the end-of-file character). If the file does not exist, the shell creates it.
  • <>Word — Opens the file specified by the Word parameter for reading and writing as standard input.
  • <<[``-]Word — Reads each line of shell input until it locates a line containing only the value of the Word parameter or an end-of-file character. The shell does not perform parameter substitution, command substitution, or file name substitution on the file specified. The resulting document, called a here document, becomes the standard input. If any character of the Word parameter is quoted, no interpretation is placed upon the characters of the document.

The here document is treated as a single word that begins after the next newline character and continues until there is a line containing only the delimiter, with no trailing blank characters. Then the next here document, if any, starts. The format is as follows:

text
[n]<<word
   here document
delimiter

If any character in word is quoted, the delimiter is formed by removing the quote on word. The here document lines will not be expanded. Otherwise, the delimiter is the word itself. If no characters in word are quoted, all lines of the here document will be expanded for parameter expansion, command substitution, and arithmetic expansion.

The shell performs parameter substitution for the redirected data. To prevent the shell from interpreting the \, $, and single quotation mark (’) characters and the first character of the Word parameter, precede the characters with a \ character.

If a hyphen (-) is appended to <<, the shell strips all leading tabs from the Word parameter and the document.

  • <&Digit — Duplicates standard input from the file descriptor specified by the Digit parameter
  • >& Digit — Duplicates standard output in the file descriptor specified by the Digit parameter
  • <&- — Closes standard input
  • >&- — Closes standard output
  • <&p — Moves input from the co-process to standard input
  • >&p — Moves output to the co-process to standard output

If one of these redirection options is preceded by a digit, then the file descriptor number referred to is specified by the digit (instead of the default 0 or 1). In the following example, the shell opens file descriptor 2 for writing as a duplicate of file descriptor 1:

text
... 2>&1

The order in which redirections are specified is significant. The shell evaluates each redirection in terms of the (FileDescriptor, File) association at the time of evaluation. For example, in the statement:

text
... 1>File 2>&1

the file descriptor 1 is associated with the file specified by the File parameter. The shell associates file descriptor 2 with the file associated with file descriptor 1 (File). If the order of redirections were reversed, file descriptor 2 would be associated with the terminal (assuming file descriptor 1 had previously been) and file descriptor 1 would be associated with the file specified by the File parameter.

If a command is followed by an ampersand (&) and job control is not active, the default standard input for the command is the empty file /dev/null. Otherwise, the environment for the execution of a command contains the file descriptors of the invoking shell as modified by input and output specifications.

Related concepts

Input and output redirection The AIX operating system allows you to manipulate the input and output (I/O) of data to and from your system by using specific I/O commands and symbols.

Related tasks

Redirecting output to inline input (here) documents You can redirect output to inline input (here) documents.

Coprocess facility:

The Korn shell, or POSIX shell, allows you to run one or more commands as background processes. These commands, run from within a shell script, are called coprocesses.

Designate a coprocess by placing the |& operator after a command. Both standard input and output of the command are piped to your script.

A coprocess must meet the following restrictions:

  • Include a newline character at the end of each message

  • Send each output message to standard output

  • Clear its standard output after each message

The following example demonstrates how input is passed to and returned from a coprocess:

text
echo "Initial process"
./FileB.sh |&
read -p a b c d
echo "Read from coprocess: $a $b $c $d"
print -p "Passed to the coprocess"
read -p a b c d
echo "Passed back from coprocess: $a $b $c $d"
FileB.sh
   echo "The coprocess is running"
   read a b c d
   echo $a $b $c $d

The resulting standard output is as follows:

text
Initial process
Read from coprocess: The coprocess is running
Passed back from coprocess: Passed to the coprocess

Use the print -p command to write to the coprocess. Use the read -p command to read from the coprocess.

Related concepts

Korn shell or POSIX shell commands The Korn shell is an interactive command interpreter and command programming language. It conforms to the Portable Operating System Interface for Computer Environments (POSIX), an international standard for operating systems.

Redirection of coprocess input and output:

The standard input and output of a coprocess is reassigned to a numbered file descriptor by using I/O redirection.

For example, the command:

text
exec 5>&p

moves the input of the coprocess to file descriptor 5.

After this coprocess has completed, you can use standard redirection syntax to redirect command output to the coprocess. You can also start another coprocess. Output from both coprocesses is connected to the same pipe and is read with the read -p command. To stop the coprocess, type the following:

text
read -u5

Korn shell or POSIX shell built-in commands

Special commands are built in to the Korn shell and POSIX shell and executed in the shell process.

Unless otherwise indicated, the output is written to file descriptor 1 and the exit status is zero (0) if the command does not contain any syntax errors. Input and output redirection is permitted. There are two types of built-in commands: special built-in commands and regular built-in commands.

Special built-in commands differ from regular built-in commands in the following ways:

  • A syntax error in a special built-in command might cause the shell executing the command to end. This does not happen if you have a syntax error in a regular built-in command. If a syntax error in a special built-in command does not end the shell program, the exit value is nonzero.

  • Variable assignments specified with special built-in commands remain in effect after the command completes.

  • I/O redirections are processed after parameter assignments.

In addition, words that are in the form of a parameter assignment following the export, readonly, and typeset special commands are expanded with the same rules as a parameter assignment. Tilde substitution is performed after the =, and word-splitting and file name substitution are not performed.

Related concepts

Korn shell or POSIX shell commands The Korn shell is an interactive command interpreter and command programming language. It conforms to the Portable Operating System Interface for Computer Environments (POSIX), an international standard for operating systems. 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.

Related reference

List of Korn shell or POSIX shell special built-in commands Special commands are built into the Korn shell and POSIX shell and executed in the shell process. Korn shell or POSIX shell regular built-in commands The following is a list of the Korn shell or POSIX shell regular built-in commands.

Special built-in command descriptions for the Korn shell or POSIX shell:

Special commands are built into the Korn shell and POSIX shell and executed in the shell process.

The special built-in commands of the Korn shell are described below:

: eval newgrp shift . exec readonly times break exit return trap continue export set typeset unset

  • : [Argument ...] — Expands only arguments. It is used when a command is necessary, as in the then condition of an if command, but nothing is to be done by the command.
  • . File [Argument ...] — Reads the complete specified file and then executes the commands. The commands are executed in the current shell environment. The search path specified by the PATH variable is used to find the directory containing the specified file. If any arguments are specified, they become the positional parameters. Otherwise, the positional parameters are unchanged. The exit status is the exit status of the most recent command executed. See “Parameter substitution in the Korn shell or POSIX shell” on page 220 for more information on positional parameters. Note: The .File [Argument ...] command reads the entire file before any commands are carried out. Therefore, the alias and unalias commands in the file do not apply to any functions defined in the file.
  • break [n] — Exits from the enclosing for, while, until, or select loop, if one exists. If you specify the n parameter, the command breaks the number of levels specified by the n parameter. The value of n is any integer equal to or greater than 1.
  • continue [n] — Resumes the next iteration of the enclosing for, while, until, or select loop. If you specify the n parameter, the command resumes at the nth enclosing loop. The value of n is any integer equal to or greater than 1.
  • eval [Argument ...] — Reads the specified arguments as input to the shell and executes the resulting command or commands.
  • exec [Argument ...] — Executes the command specified by the argument in place of this shell (without creating a new process). Input and output arguments can appear and affect the current process. If you do not specify an argument, the exec command modifies file descriptors as prescribed by the input and output redirection list. In this case, any file descriptor numbers greater than 2 that are opened with this mechanism are closed when invoking another program.
  • exit [n] — Exits the shell with the exit status specified by the n parameter. The n parameter must be an unsigned decimal integer with range 0-255. If you omit the n parameter, the exit status is that of the most recent command executed. An end-of-file character also exits the shell unless the ignoreeof option of the set special command is turned on.
  • export -p [Name[= Value]] ... — Marks the specified names for automatic export to the environment of subsequently executed commands. -p writes to standard output the names and values of all exported variables, in the following format: "export %s= %s\n", <name> <value>
  • newgrp [Group] — Equivalent to the exec/usr/bin/newgrp [Group] command. Note: This command does not return.
  • readonly -p [Name[= Value]]

... Marks the names specified by the Name parameter as read-only. These names cannot be changed by subsequent assignment.

-p writes to standard output the names and values of all exported variables, in the following format:

text
"export %s= %s\n", <name> <value>

return [n] Causes a shell function to return to the invoking script. The return status is specified by the n parameter. If you omit the n parameter, the return status is that of the most recent command executed. If you invoke the return command outside of a function or a script, then it is the same as an exit command.

  • set [+ |``-abCefhkmnostuvx ]

[+ |``-o Option]... [+ |``-AName] [Argument ...] If no options or arguments are specified, the set command writes the names and values of all shell variables in the collation sequence of the current locale. When options are specified, they will set or unset attributes of the shell, described as follows: -A Array assignment. Unsets the Name parameter and assigns values sequentially from the specified Argument parameter list. If the +A flag is used, the Name parameter is not unset first. -a Automatically exports all subsequent parameters that are defined. -b Notifies the user asynchronously of background job completions. -C Equivalent to set -o noclobber. -e Executes the ERR trap, if set, and exits if a command has a nonzero exit status unless the simple command is: + contained in an && or || list + the command immediately following if, while or until + contained in the pipeline following ! This mode is disabled while reading profiles. -f Disables file name substitution. -h Designates each command as a tracked alias when first encountered. -k Places all parameter-assignment arguments in the environment for a command, not only those arguments that precede the command name. -m Runs background jobs in a separate process and prints a line upon completion. The exit status of background jobs is reported in a completion message. On systems with job control, this flag is turned on automatically for interactive shells. For more information, see Job control in the Korn shell or POSIX shell. -n Reads commands and checks them for syntax errors, but does not execute them. This flag is ignored for interactive shells.

-o Option Prints current option settings and an error message if you do not specify an argument. You can set more than one option on a single ksh command line. If the +o flag is used, the specified option is unset. When arguments are specified, they will cause positional parameters to be set or unset. Arguments, as specified by the Option variable, can be one of the following: allexport Same as the -a flag. bgnice Runs all background jobs at a lower priority. This is the default mode. emacs Enters an emacs-style inline editor for command entry. errexit Same as the -e flag. gmacs Enters a gmacs-style inline editor for command entry. ignoreeof Does not exit the shell when it encounters an end-of-file character. To exit the shell, you must use the exit command or press the Ctrl-D key sequence more than 11 times. keyword Same as the -k flag. Note: This flag is for backward compatibility with the Bourne shell only. Its use is strongly discouraged. markdirs Appends a backslash / to all directory names that are a result of file name substitution. monitor Same as the -m flag. noclobber Prevents redirection from truncating existing files. When you specify this option, a vertical bar must follow the redirection symbol (>|) to truncate a file. noexec Same as the -n flag. noglob Same as the -f flag. nolog Prevents function definitions in .profile and $ENV files from being saved in the history file. nounset Same as the -u flag. privileged Same as the -p flag.

trackall Same as the -h flag. verbose Same as the -v flag. vi Enters the insert mode of a vi-style inline editor for command entry. Entering escape character 033 puts the editor into the move mode. A return sends the line. viraw Processes each character as it is typed in vi mode. xtrace Same as the -x flag. -p Disables processing of the $HOME/.profile file and uses the /etc/suid_profile file instead of the ENV file. This mode is enabled whenever the effective user ID (UID) or group ID (GID) is not equal to the real UID or GID. Turning off this option sets the effective UID or GID to the real UID and GID. Note: The system does not support the -p option because the operating system does not support setuid shell scripts. -s Sorts the positional parameters lexicographically. -t Exits after reading and executing one command. Note: This flag is for backward compatibility with the Bourne shell only. Its use is strongly discouraged. -u Treats unset parameters as errors when substituting. -v Prints shell input lines as they are read. -x Prints commands and their arguments as they are executed. - Turns off the -x and -v flags and stops examining arguments for flags. — Prevents any flags from being changed. This option is useful in setting the $1 parameter to a value beginning with -. If no arguments follow this flag, the positional parameters are not set.

Preceding any of the set command flags with a + rather than a - turns off the flag. You can use these flags when you invoke the shell. When 'set +o' is invoked without any arguments, it displays the current option settings in a format that is suitable for re-input to the shell as commands that achieve the same option setting. The current set of flags is found in the $- parameter. Unless you specify the -A flag, the remaining arguments are positional parameters and are assigned, in order, to $1, $2, ..., and so on. If no arguments are given, the names and values of all named parameters are printed to standard output.

shift [n] Renames the positional parameters, beginning with $n+1 ... through $1 .... The default value of the n parameter is 1. The n parameter is any arithmetic expression that evaluates to a nonnegative number less than or equal to the $# parameter.

times Prints the accumulated user and system times for the shell and for processes run from the shell.

  • trap [Command] [Signal] ... — Runs the specified command when the shell receives the specified signal or signals. The Command parameter is read once when the trap is set and once when the trap is taken. The Signal parameter can be given as a number or as the name of the signal. Trap commands are executed in order of signal number. Any attempt to set a trap on a signal that was ignored on entry to the current shell is ineffective. If the command is -, all traps are reset to their original values. If you omit the command and the first signal is a numeric signal number, then the ksh command resets the value of the Signal parameter or parameters to the original values. Note: If you omit the command and the first signal is a symbolic name, the signal is interpreted as a command. If the value of the Signal parameter is the ERR signal, the specified command is carried out whenever a command has a nonzero exit status. If the signal is DEBUG, then the specified command is carried out after each command. If the value of the Signal parameter is the 0 or EXIT signal and the trap command is executed inside the body of a function, the specified command is carried out after the function completes. If the Signal parameter is 0 or EXIT for a trap command set outside any function, the specified command is carried out on exit from the shell. Note: If a script receives a SIGINT signal within a function, the EXIT signal cannot be trapped when the shell exits. The trap command with no arguments prints a list of commands associated with each signal number. If the command specified is NULL, indicated as "" (empty quotes), then the ksh command will ignore the signal. For more information about how the Korn shell or the POSIX shell reads a character as a regular character, see “Quotation of characters in the Korn shell or POSIX shell” on page 213. For a complete list of Signal parameter values used in the trap command without the SIG prefix, see the sigaction, sigvec, or signal subroutine in the Technical Reference: Base Operating System and Extensions, Volume 2.
  • typeset [+HLRZfilrtux [n]]

[Name[=Value]] ... Sets attributes and values for shell parameters. When invoked inside a function, a new instance of the Name parameter is created. The parameter value and type are restored when the function completes. You can specify the following flags with the typeset command: -H Provides AIX-to-host-file mapping on non-AIX machines. -L Left-justifies and removes leading blanks from the Value parameter. If the n parameter has a nonzero value, it defines the width of the field; otherwise, it is determined by the width of the value of its first assignment. When the parameter is assigned, it is filled on the right with blanks or truncated, if necessary, to fit into the field. Leading zeros are removed if the -Z flag is also set. The -R flag is turned off. -R Right-justifies and fills with leading blanks. If the n parameter has a nonzero value, it defines the width of the field; otherwise, it is determined by the width of the value of its first assignment. The field remains filled with blanks or is truncated from the end if the parameter is reassigned. The L flag is turned off. -Z Right-justifies and fills with leading zeros if the first nonblank character is a digit and the -L flag has not been set. If the n parameter has a nonzero value, it defines the width of the field; otherwise, it is determined by the width of the value of its first assignment. -f Indicates that the names refer to function names rather than parameter names. No assignments can be made and the only other valid flags are -t, -u, and -x . The -t flag turns on execution tracing for this function. The -u flag causes this function to be marked undefined. The FPATH variable is searched to find the function definition when the function is referenced. The -x flag allows the function definition to remain in effect across shell scripts that are not a separate invocation of the ksh command. -i Identifies the parameter as an integer, making arithmetic faster. If the n parameter has a nonzero value, it defines the output arithmetic base; otherwise, the first assignment determines the output base. -l Converts all uppercase characters to lowercase. The -u uppercase conversion flag is turned off. -r Marks the names specified by the Name parameter as read-only. These names cannot be changed by subsequent assignment.

-t Tags the named parameters. Tags can be defined by the user and have no special meaning to the shell. -u Converts all lowercase characters to uppercase characters. The -l lowercase flag is turned off. -x Marks the name specified by the Name parameter for automatic export to the environment of subsequently executed commands. Using a + rather than a - turns off the typeset command flags. If you do not specify Name parameters but do specify flags, a list of names (and optionally the values) of the parameters that have these flags set is printed. (Using a + rather than a - keeps the values from being printed.) If you do not specify any names or flags, the names and attributes of all parameters are printed.

unset [-fv ] Name ... Unsets the values and attributes of the parameters given by the list of names. If -v is specified, Name refers to a variable name, and the shell will unset it and remove it from the environment. Read-only variables cannot be unset. Unsetting the ERRNO, LINENO, MAILCHECK, OPTARG, OPTIND, RANDOM, SECONDS, TMOUT, and underscore (_) variables removes their special meanings even if they are subsequently assigned.

If the -f flag is set, then Name refers to a function name, and the shell will unset the function definition.

Regular built-in command descriptions for the Korn shell or POSIX shell:

The built-in commands for the Korn or POSIX shells are described here.

The Korn shell provides the following regular built-in commands:

alias fg print ulimit bg getopts pwd umask cd jobs read unalias command kill setgroups wait echo let setsenv test whence fc

  • alias [-t ] [-x ]

[AliasName[= String]] ... Creates or redefines alias definitions or writes existing alias definitions to standard output.

For more information, see the alias command.

bg [JobID...] Puts each specified job into the background. The current job is put in the background if a JobID parameter is not specified. See Job control in the Korn shell or POSIX shell for more information about job control.

For more information about running jobs in the background, see the bg command.

cd [Argument]

  • cd Old New — This command can be in either of two forms. In the first form, it changes the current directory to the one specified by the Argument parameter. If the value of the Argument parameter is a hyphen (-), the directory is changed to the previous directory. The HOME shell variable is the default value of the Argument parameter. The PWD variable is set to the current directory. The CDPATH shell variable defines the search path for the directory containing the value of the Argument parameter. Alternative directory names are separated by a colon (:). The default path is null, specifying the current directory. The current directory is specified by a null path name, which appears immediately after the equal sign or between the colon delimiters anywhere in the path list. If the specified argument begins with a slash (/), the search path is not used. Otherwise, each directory in the path is searched for the argument. The second form of the cd command substitutes the string specified by the New variable for the string specified by the Old variable in the current directory name, PWD, and tries to change to this new directory.
  • command [-p ] CommandName [Argument

...] command [-v | -V ] CommandName Causes the shell to treat the specified command and arguments as a simple command, suppressing shell-function lookup.

For more information, see the command command.

echo [String ...] Writes character strings to standard output. See the echo command for usage and description. The -n flag is not supported.

fc [-r ] [-e Editor] [First [Last]] fc -l [-n ] [-r ] [First [Last]] fc -s [Old= New] [First] Displays the contents of your command history file or invokes an editor to modify and re-execute commands previously entered in the shell.

For more information, see the fc command.

fg [JobID] Brings each job specified into the foreground. If you do not specify any jobs, the command brings the current job into the foreground.

For more information about running jobs in the foreground, see the fg command.

getopts OptionString Name [Argument ...] Checks the Argument parameter for legal options.

For more information, see the getopts command.

jobs [-l | -n | -p ] [JobID ...] Displays the status of jobs started in the current shell environment. If no specific job is specified with the JobID parameter, status information for all active jobs is displayed. If a job termination is reported, the shell removes that job's process ID from the list of those known by the current shell environment.

For more information, see the jobs command.

kill [ -s { SignalName | SignalNumber } ] ProcessID... Sends a signal (by default, the SIGTERM signal) to a running process. This default action normally stops processes. If you want to stop a process, specify the process ID (PID) in the ProcessID variable. The shell reports the PID of each process that is running in the background (unless you start more than one process in a pipeline, in which case the shell reports the number of the last process). You can also use the ps command to find the process ID number of commands. kill [ -SignalName | -SignalNumber ] ProcessID... kill -l [ ExitStatus ] Lists signal names.

For more information, see the kill command.

let Expression ... Evaluates specified arithmetic expressions. The exit status is 0 if the value of the last expression is nonzero, and 1 otherwise. See Arithmetic evaluation in the Korn shell or POSIX shell for more information.

  • print [-Rnprsu [n]]

[Argument ...] Prints shell output. If you do not specify any flags, or if you specify the hyphen (-) or double hyphen (—) flags, the arguments are printed to standard output as described by the echo command. The flags do the following: -R Prints in raw mode (the escape conventions of the echo command are ignored). The -R flag prints all subsequent arguments and flags other than -n. -n Prevents a newline character from being added to the output. -p Writes the arguments to the pipe of the process run with |& instead of to standard output. -r Prints in raw mode. The escape conventions of the echo command are ignored. -s Writes the arguments to the history file instead of to standard output. -u Specifies a one-digit file descriptor unit number, n, on which the output is placed. The default is 1.

pwd Equivalent to print -r - $PWD. Note: The internal Korn shell pwd command does not support symbolic links.

read [-prsu [n ]] [Name?Prompt] [Name...] Takes shell input. One line is read and broken up into fields, using the characters in the IFS variable as separators.

For more information, see the read command.

setgroups Executes the /usr/bin/setgroups command, which runs as a separate shell. See the setgroups command for information on this command. There is one difference, however. The setgroups built-in command invokes a subshell, but the setgroups command replaces the currently executing shell. Because the built-in command is supported only for compatibility, it is recommended that scripts use the absolute path name /usr/bin/setgroups rather than the shell built-in command.

setsenv Executes the /usr/bin/setsenv command, which replaces the currently executing shell. See the setsenv command for information on this command.

test Same as [expression]. See Conditional expressions for the Korn shell or POSIX shell for usage and description.

  • ulimit [-HSacdfmst ]

[Limit] Sets or displays user-process resource limits as defined in the /etc/security/limits file. This file contains the following default limits:

text
fsize = 2097151
core = 2048
cpu = 3600
data = 131072
rss = 65536
stack = 8192
threads = -1

These values are used as default settings when a user is added to the system. The values are set with the mkuser command when the user is added to the system or changed with the chuser command.

Limits are categorized as either soft or hard. Users might change their soft limits, up to the maximum set by the hard limits, with the ulimit command. You must have root user authority to change resource hard limits.

Many systems do not contain one or more of these limits. The limit for a specified resource is set when the Limit parameter is specified. The value of the Limit parameter can be a number in the unit specified with each resource or the value unlimited. You can specify the following ulimit command flags: -H Specifies that the hard limit for the given resource is set. If you have root user authority, you can increase the hard limit. Any user can decrease it. -S Specifies that the soft limit for the given resource is set. A soft limit can be increased up to the value of the hard limit. If neither the -H or -S options are specified, the limit applies to both. -a Lists all of the current resource limits. -c Specifies the number of 512-byte blocks on the size of core dumps. -d Specifies the size, in KB, of the data area. -f Specifies the number of 512-byte blocks for files written by child processes (files of any size can be read). -m Specifies the number of KB for the size of physical memory. -n Specifies the limit on the number of file descriptors a process might have open. -r Specifies the limit on the number of threads per process. -s Specifies the number of KB for the size of the stack area. -t Specifies the number of seconds to be used by each process.

The current resource limit is printed when you omit the Limit variable. The soft limit is printed unless you specify the -H flag. When you specify more than one resource, the limit name and unit is printed before the value. If no option is given, the -f flag is assumed. When you change the value, set both hard and soft limits to Limit unless you specify -H or -S.

For more information about user and system resource limits, see the getrlimit, setrlimit, or vlimit subroutine.

umask [-S ] [Mask] Determines file permissions. This value, along with the permissions of the creating process, determines a file's permissions when the file is created. The default is 022. If the Mask parameter is not specified, the umask command displays to standard output the file-mode creation mask of the current shell environment.

For more information about file permissions, see the umask command.

unalias { -a | AliasName... } Removes the definition for each alias name specified, or removes all alias definitions if the -a flag is used. Alias definitions are removed from the current shell environment.

For more information, see the unalias command.

wait [ProcessID...] Waits for the specified job and terminates. If you do not specify a job, the command waits for all currently active child processes. The exit status from this command is that of the process for which it waits.

For more information, see the wait command.

  • whence [-pv ] Name ... — Indicates, for each name specified, how it would be interpreted if used as a command name. When used without either flag, whence will display the absolute path name, if any, that corresponds to each name. -p Performs a path search for the specified name or names even if these are aliases, functions, or reserved words. -v Produces a more verbose report that specifies the type of each name.