[AIX 운영 체제와 장치 관리 23] Korn 셸 (4) — 작업 제어, 인라인 편집(emacs·vi 모드), Korn 셸 명령·복합 명령·시작·환경·함수·명령 기록, 별명과 틸드 치환
https://archive.horanglab.com/posts/aix-osdev-23
핵심 정리
set -m이면 파이프라인마다 작업이 되고%번호,%문자열,%?문자열,%%·%+(현재),%-(이전)로 가리킵니다. Ctrl-Z로 멈추고 bg·fg로 옮기며, 멈춘 작업이 있으면 exit를 한 번 더 해야 끝납니다.- 인라인 편집은
set -o emacs·gmacs·vi로 켜며 VISUAL·EDITOR 값으로도 자동 선택됩니다. 창 너비는 COLUMNS(기본 80)이고 줄이 넘치면>,<,*표시가 붙습니다. - 명령은 치환 → 슬래시 여부 → 특수 내장 → 사용자 함수 → 일반 내장 → exec 순서로 처리하며, 기본 PATH는
/usr/bin:(현재 디렉터리 포함)입니다.XPG_SUS_ENV=ON,OCTAL_CONST=ON으로 8진·16진 상수를 인식시킵니다. - 로그인 셸은
/etc/profile→.profile→ ENV 파일 순서로 읽습니다. 함수는 변수·작업 디렉터리·별명·열린 파일을 호출자와 공유하고 위치 매개변수·#·typeset 지역 변수·옵션·trap은 공유하지 않습니다. - 별명은 비대화식 ksh(스크립트,
ksh -c)에서는 지원하지 않습니다.set -h로 추적 별명을 켜고,~,~+,~-,~user로 틸드 치환을 합니다.
| 항목 | 내용 |
|---|---|
| 버전 | AIX 6.1 (5.3판과 거의 같음) |
| 원문 | Operating system and device management — 5.3판 425437쪽, 6.1판 236248쪽 |
| 관련 명령어 | jobs, bg, fg, set -m, set -o emacs·vi, stty tostop, fc, alias, unalias, typeset -xf |
| 관련 파일 | /etc/profile, $HOME/.profile, $HOME/.sh_history, /etc/passwd |
Korn 셸(POSIX 셸)은 명령 순서, 곧 작업을 제어하는 기능을 제공합니다.
set -m 특수 명령을 실행하면 Korn 셸은 파이프라인마다 작업을 연결합니다. 셸은 jobs 명령이 출력하는 현재 작업 표를 유지하고 작업에 작은 정수 번호를 매깁니다.
앰퍼샌드(&)로 작업을 백그라운드에서 시작하면 셸은 다음과 같은 줄을 출력합니다.
[1] 1234
이 출력은 백그라운드에서 시작한 작업이 작업 번호 1이라는 뜻입니다. 또 그 작업에 프로세스 ID가 1234인 (최상위) 프로세스가 하나 있다는 뜻입니다.
작업을 실행하다가 다른 일을 하고 싶으면 Ctrl-Z 키를 누릅니다. 이 키는 현재 작업에 STOP 신호를 보냅니다. 셸은 보통 작업이 멈췄다고 알리고 셸 프롬프트를 보여 줍니다. 그러면 이 작업의 상태를 바꾸고(bg 명령으로 백그라운드에 넣는 등), 다른 명령을 실행하고, 결국 fg 명령으로 작업을 포그라운드로 되돌릴 수 있습니다. Ctrl-Z는 바로 효과가 나며, 누르면 셸이 대기 중인 출력과 읽지 않은 입력을 버린다는 점에서 인터럽트와 비슷합니다.
백그라운드에서 실행 중인 작업은 터미널에서 읽으려고 하면 멈춥니다. 백그라운드 작업은 보통 출력을 낼 수 있습니다. stty tostop 명령으로 이를 끌 수 있습니다. 이 터미널 옵션을 설정하면 백그라운드 작업은 출력을 내거나 입력을 읽으려 할 때 멈춥니다.
Korn 셸에서 작업은 여러 방법으로 가리킬 수 있습니다. 작업에 속한 아무 프로세스의 프로세스 ID로, 또는 다음 가운데 하나로 가리킵니다.
| 표기 | 가리키는 작업 |
|---|---|
%Number |
주어진 번호의 작업 |
%String |
명령행이 String으로 시작하는 작업 |
%?String |
명령행에 String이 든 작업 |
%% |
현재 작업 |
%+ |
%%와 같음 |
%- |
이전 작업 |
이 셸은 프로세스 상태 변화를 바로 알아챕니다. 보통 작업이 막혀 더 진행할 수 없게 되면 알려 줍니다. 셸은 하던 일을 방해하지 않도록 프롬프트를 출력하기 직전에 알립니다.
모니터 모드가 켜져 있으면 끝난 백그라운드 작업마다 CHLD 신호에 설정한 trap이 실행됩니다.
작업이 멈춰 있거나 실행 중일 때 (exit를 입력하거나 Ctrl-D를 눌러) 셸을 떠나려 하면 시스템은 There are stopped (running) jobs. 메시지로 경고합니다. jobs 명령으로 어떤 작업이 해당하는지 봅니다. 바로 다시 끝내려 하면 셸은 경고 없이 멈춘 작업과 실행 중인 작업을 끝냅니다.
신호 처리
호출한 명령 뒤에 앰퍼샌드(&)가 오고 작업 모니터 옵션이 활성이 아니면 그 명령의 SIGINT와 SIGQUIT 신호는 무시됩니다. 그렇지 않으면 신호는 셸이 부모에게서 물려받은 값을 가집니다.
셸이 포그라운드 명령이 끝나기를 기다리는 동안 trap이 설정된 신호를 받으면, 그 신호와 연결된 trap은 포그라운드 명령이 끝난 뒤에야 실행됩니다. 그래서 CHILD 신호의 trap은 포그라운드 작업이 끝날 때까지 실행되지 않습니다.
Korn 셸이나 POSIX 셸의 인라인 편집
보통은 터미널 장치에서 명령행을 입력하고 줄 바꿈 문자(RETURN이나 LINE FEED)로 끝냅니다. emacs, gmacs, vi 인라인 편집 옵션을 켜면 명령행을 편집할 수 있습니다.
다음 명령으로 편집 모드에 들어갑니다.
| 명령 | 설명 |
|---|---|
set -o emacs |
emacs 편집 모드에 들어가 emacs 방식 인라인 편집기를 시작합니다. |
set -o gmacs |
emacs 편집 모드에 들어가 gmacs 방식 인라인 편집기를 시작합니다. |
set -o vi |
vi 편집 모드에 들어가 vi 방식 인라인 편집기를 시작합니다. |
VISUAL이나 EDITOR 변수에 이 옵션 이름 가운데 하나로 끝나는 값을 할당할 때마다 편집 옵션이 자동으로 선택됩니다.
참고: 편집 기능을 쓰려면 터미널이 RETURN을 줄 바꿈 없는 캐리지 리턴으로 받아야 합니다. 스페이스는 화면의 현재 문자를 덮어써야 합니다.
각 편집 모드는 현재 줄에 창을 엽니다. 창 너비는 COLUMNS 변수가 정의돼 있으면 그 값이고, 아니면 80자입니다. 줄이 창 너비에서 2를 뺀 것보다 길면 창 끝에 표시를 보여 알립니다. 커서가 움직여 창 경계에 닿으면 창은 커서를 중심으로 옮겨집니다. 표시는 다음과 같습니다.
>— 줄이 창 오른쪽으로 이어집니다.<— 줄이 창 왼쪽으로 이어집니다.*— 줄이 창 양쪽으로 이어집니다.
각 편집 모드의 검색 명령으로 Korn 셸 기록 파일에 접근합니다. 문자열만 맞춥니다. 문자열의 첫 문자가 캐럿(^)이면 줄의 첫 문자부터 맞아야 합니다.
관련 개념
- Korn 셸 또는 POSIX 셸 명령
emacs 편집 모드
emacs나 gmacs 옵션을 켜면 emacs 편집 모드에 들어갑니다. 두 모드의 차이는 Ctrl-T 편집 명령을 처리하는 방식뿐입니다.
편집하려면 고칠 곳으로 커서를 옮겨 필요한 대로 문자나 단어를 넣거나 지웁니다. 모든 편집 명령은 제어 문자나 이스케이프 시퀀스입니다.
편집 명령은 (줄 처음뿐 아니라) 줄 어디서나 동작합니다. 따로 적지 않은 한 편집 명령 뒤에 Enter 키나 줄 바꿈(아래 화살표) 키를 누르지 않습니다.
| 키 | 동작 |
|---|---|
Ctrl-F |
커서를 한 문자 앞(오른쪽)으로 옮깁니다. |
Esc-F |
커서를 한 단어(문자·숫자·밑줄로만 된 문자열) 앞으로 옮깁니다. |
Ctrl-B |
커서를 한 문자 뒤(왼쪽)로 옮깁니다. |
Esc-B |
커서를 한 단어 뒤로 옮깁니다. |
Ctrl-A |
커서를 줄 처음으로 옮깁니다. |
Ctrl-E |
커서를 줄 끝으로 옮깁니다. |
Ctrl-] c |
현재 줄에서 지정한 문자 c까지 커서를 앞으로 옮깁니다. |
Esc-Ctrl-] c |
현재 줄에서 지정한 문자 c까지 커서를 뒤로 옮깁니다. |
Ctrl-X Ctrl-X |
커서와 표시(mark)를 맞바꿉니다. |
| ERASE | 앞 문자를 지웁니다(stty 명령으로 정의한 사용자 지우기 문자, 보통 Ctrl-H). |
Ctrl-D |
현재 문자를 지웁니다. |
Esc-D |
현재 단어를 지웁니다. |
Esc-Backspace |
앞 단어를 지웁니다. |
Esc-H |
앞 단어를 지웁니다. |
Esc-Delete |
앞 단어를 지웁니다. 인터럽트 문자가 Delete 키이면 동작하지 않습니다. |
Ctrl-T |
emacs 모드에서는 현재 문자와 다음 문자를, gmacs 모드에서는 앞의 두 문자를 맞바꿉니다. |
Ctrl-C |
현재 문자를 대문자로 바꿉니다. |
Esc-C |
현재 단어를 대문자로 바꿉니다(원문 Capitalizes). |
Esc-L |
현재 단어를 소문자로 바꿉니다. |
Ctrl-K |
커서부터 줄 끝까지 지웁니다. 앞에 현재 커서 위치보다 작은 숫자 매개변수가 오면 그 위치부터 커서까지, 큰 값이 오면 커서부터 그 위치까지 지웁니다. |
Ctrl-W |
커서부터 표시까지 지웁니다. |
Esc-P |
커서부터 표시까지의 영역을 스택에 넣습니다. |
| KILL | stty 명령으로 정의한 사용자 죽이기 문자(보통 Ctrl-G나 @). 현재 줄 전체를 지웁니다. 죽이기 문자를 두 번 연달아 입력하면 이후의 죽이기 문자는 줄 바꿈을 일으킵니다(종이 터미널에서 쓸모 있음). |
Ctrl-Y |
줄에서 마지막으로 지운 항목을 되살립니다(yank). |
Ctrl-L |
줄을 바꾸고 현재 줄을 출력합니다. |
Ctrl-@ |
(널 문자) 표시를 설정합니다. |
Esc-space |
표시를 설정합니다. |
Ctrl-J |
(줄 바꿈) 현재 줄을 실행합니다. |
Ctrl-M |
(Return) 현재 줄을 실행합니다. |
| EOF | 파일 끝 문자(보통 Ctrl-D)는 현재 줄이 비어 있을 때만 파일 끝으로 처리합니다. |
Ctrl-P |
앞 명령을 가져옵니다. 누를 때마다 시간상 더 앞의 명령으로 갑니다. 여러 줄 명령의 첫 줄이 아니면 한 줄 위로 갑니다. |
Esc-< |
가장 오래된 기록 줄을 가져옵니다. |
Esc-> |
가장 최근 기록 줄을 가져옵니다. |
Ctrl-N |
다음 명령행을 가져옵니다. 누를 때마다 시간상 다음 명령행으로 갑니다. |
Ctrl-R String |
String이 든 이전 명령행을 기록에서 거꾸로 찾습니다. 값 0을 주면 앞으로 찾습니다. 문자열은 Enter나 줄 바꿈 문자로 끝납니다. 문자열 앞에 캐럿(^)이 있으면 일치하는 줄은 String으로 시작해야 합니다. String을 생략하면 가장 최근 String이 든 다음 명령행으로 가며, 이때 값 0은 검색 방향을 뒤집습니다. |
Ctrl-O |
(Operate) 현재 줄을 실행하고 기록 파일에서 현재 줄 다음 줄을 가져옵니다. |
Esc Digits |
(Escape) 숫자 매개변수를 정의합니다. 숫자는 다음 명령의 매개변수가 됩니다. 매개변수를 받는 명령은 Ctrl-F, Ctrl-B, ERASE, Ctrl-C, Ctrl-D, Ctrl-K, Ctrl-R, Ctrl-P, Ctrl-N, Ctrl-], Esc-., Esc-Ctrl-], Esc-_, Esc-B, Esc-C, Esc-D, Esc-F, Esc-H, Esc-L, Esc-Ctrl-H입니다. |
Esc Letter |
(소프트 키) 별명 목록에서 _Letter라는 별명을 찾아, 있으면 그 값을 입력 큐에 넣습니다. Letter는 이스케이프 기능 가운데 하나를 가리키면 안 됩니다. |
Esc-[ Letter |
(소프트 키) 별명 목록에서 __Letter(밑줄 둘)라는 별명을 찾아, 있으면 그 값을 입력 큐에 넣습니다. 많은 터미널에서 기능 키를 프로그래밍하는 데 쓸 수 있습니다. |
Esc-. |
앞 명령의 마지막 단어를 줄에 넣습니다. 앞에 숫자 매개변수가 오면 마지막 단어 대신 그 번호의 단어를 넣습니다. |
Esc-_ |
Esc-.와 같습니다. |
Esc-* |
현재 단어에 파일 이름 치환을 시도합니다. 단어가 어떤 파일과도 맞지 않거나 특수 패턴 문자가 없으면 별표(*)를 덧붙입니다. |
Esc-Esc |
파일 이름 완성. 현재 단어 뒤에 별표를 붙여 맞는 모든 파일 이름의 가장 긴 공통 접두사로 현재 단어를 바꿉니다. 일치가 하나뿐이면 디렉터리에는 슬래시(/)를, 디렉터리가 아니면 스페이스를 덧붙입니다. |
Esc-= |
별표(*)를 덧붙인 것처럼 현재 단어 패턴과 맞는 파일을 나열합니다. |
Ctrl-U |
다음 명령의 매개변수에 4를 곱합니다. |
\\ |
다음 문자를 이스케이프합니다. 편집 문자와 ERASE, KILL, INTERRUPT(보통 Delete 키) 문자는 앞에 백슬래시를 붙이면 명령행이나 검색 문자열에 넣을 수 있습니다. 백슬래시는 다음 문자의 편집 기능(있으면)을 없앱니다. |
Ctrl-V |
셸 버전을 보여 줍니다. |
Esc-# |
줄 처음에 샵 기호(#)를 넣고 줄을 실행합니다. 이렇게 하면 기록 파일에 주석이 들어갑니다. |
vi 편집 모드
vi 편집 모드에는 입력 방식이 두 가지 있습니다.
- 입력 모드. 명령을 입력하면 vi 편집기는 입력 모드입니다.
- 제어 모드. Esc 키를 누르면 제어 모드에 들어갑니다.
대부분의 제어 명령은 명령 앞에 선택적 반복 Count 매개변수를 받습니다. 대부분의 시스템에서 vi 모드에 들어가면 처음에는 정규(canonical) 처리가 켜져 있습니다. 다음 가운데 하나 이상이 참이면 명령을 다시 에코합니다.
- 속도가 1200보 이상입니다.
- 명령에 제어 문자가 들어 있습니다.
- 프롬프트를 출력한 뒤 1초가 지나지 않았습니다.
Esc 문자는 명령의 나머지에 대해 정규 처리를 끝내며, 그 뒤 명령행을 고칠 수 있습니다. 이 방식은 정규 처리의 장점과 원시 모드의 미리 입력 에코를 함께 누립니다. viraw 옵션도 설정하면 정규 처리는 늘 꺼집니다. 이 모드는 두 가지 줄 끝 구분자를 지원하지 않는 시스템에서는 암묵적이며 일부 터미널에 도움이 될 수 있습니다.
vi 편집 명령은 다음 범주로 묶입니다.
입력 편집 명령
Korn 셸의 입력 편집 명령은 다음과 같습니다.
참고: 기본적으로 편집기는 입력 모드입니다.
- ERASE — 앞 문자를 지웁니다(stty 명령으로 정의한 사용자 지우기 문자, 보통 Ctrl-H나
#). Ctrl-W— 공백으로 구분한 앞 단어를 지웁니다.Ctrl-D— 셸을 끝냅니다.Ctrl-V— 다음 문자를 이스케이프합니다. ERASE나 KILL 같은 편집 문자는 앞에 Ctrl-V를 붙이면 명령행이나 검색 문자열에 넣을 수 있습니다. Ctrl-V는 다음 문자의 편집 기능(있으면)을 없앱니다.\— 다음 ERASE나 KILL 문자를 이스케이프합니다.
이동 편집 명령
이동 편집 명령은 다음과 같이 커서를 옮깁니다.
[Count]l— 커서를 한 문자 앞(오른쪽)으로 옮깁니다.[Count]w— 커서를 영숫자 한 단어 앞으로 옮깁니다.[Count]W— 커서를 공백 뒤에 오는 다음 단어의 처음으로 옮깁니다.[Count]e— 커서를 현재 단어의 끝으로 옮깁니다.[Count]E— 커서를 공백으로 구분한 현재 단어의 끝으로 옮깁니다.[Count]h— 커서를 한 문자 뒤(왼쪽)로 옮깁니다.[Count]b— 커서를 한 단어 뒤로 옮깁니다.[Count]B— 커서를 공백으로 구분한 앞 단어로 옮깁니다.[Count]|— 커서를 Count로 지정한 열로 옮깁니다.[Count]fc— 현재 줄에서 다음 문자 c를 찾습니다.[Count]Fc— 현재 줄에서 앞 문자 c를 찾습니다.[Count]tc— f 뒤에 h를 한 것과 같습니다.[Count]Tc— F 뒤에 l을 한 것과 같습니다.[Count];— 마지막 한 문자 찾기 명령(f, F, t, T)을 Count번 반복합니다.[Count],— 마지막 한 문자 찾기 명령을 반대 방향으로 Count번 반복합니다.0— 커서를 줄 처음으로 옮깁니다.^— 커서를 줄의 첫 공백 아닌 문자로 옮깁니다.$— 커서를 줄 끝으로 옮깁니다.
검색 편집 명령
검색 편집 명령은 다음과 같이 명령 기록에 접근합니다.
[Count]k— 앞 명령을 가져옵니다.[Count]-— k 명령과 같습니다.[Count]j— 다음 명령을 가져옵니다. j 명령을 입력할 때마다 다음 명령으로 갑니다.[Count]+— j 명령과 같습니다.[Count]G— Count로 지정한 번호의 명령을 가져옵니다. 기본값은 가장 오래된 기록 명령입니다./String— 지정한 문자열이 든 이전 명령을 기록에서 거꾸로 찾습니다. 문자열은 RETURN이나 줄 바꿈 문자로 끝납니다. 문자열 앞에 캐럿(^)이 있으면 일치하는 줄은 String으로 시작해야 합니다. String 값이 비어 있으면 앞 문자열을 씁니다.?String—/String과 같지만 앞으로 찾습니다.n—/String이나?명령의 마지막 패턴의 다음 일치를 찾습니다.N—/String이나?명령의 마지막 패턴의 다음 일치를 반대 방향으로 찾습니다.
텍스트 수정 편집 명령
텍스트 수정 편집 명령은 다음과 같이 줄을 고칩니다.
a— 입력 모드에 들어가 현재 문자 뒤에 텍스트를 넣습니다.A— 줄 끝에 텍스트를 덧붙입니다.$a명령과 같습니다.[Count]cMotion,c[Count]Motion— 현재 문자부터 Motion이 커서를 옮길 문자까지 지우고 입력 모드에 들어갑니다. Motion이 c이면 줄 전체를 지우고 입력 모드에 들어갑니다.C— 현재 문자부터 줄 끝까지 지우고 입력 모드에 들어갑니다.c$명령과 같습니다.S— cc 명령과 같습니다.D— 현재 문자부터 줄 끝까지 지웁니다.d$명령과 같습니다.[Count]dMotion,d[Count]Motion— 현재 문자부터 Motion이 지정한 문자까지(포함) 지웁니다. Motion이 d이면 줄 전체를 지웁니다.i— 입력 모드에 들어가 현재 문자 앞에 텍스트를 넣습니다.I— 줄 처음 앞에 텍스트를 넣습니다. 0i 명령과 같습니다.[Count]P— 앞의 텍스트 수정을 커서 앞에 놓습니다.[Count]p— 앞의 텍스트 수정을 커서 뒤에 놓습니다.R— 입력 모드에 들어가 화면의 문자를 덮어씁니다.[Count]rc— 현재 커서 위치부터 Count개 문자를 c로 바꿉니다. 바꾼 뒤 커서를 앞으로 옮깁니다.[Count]x— 현재 문자를 지웁니다.[Count]X— 앞 문자를 지웁니다.[Count].— 앞의 텍스트 수정 명령을 반복합니다.[Count]~— 현재 커서 위치부터 Count개 문자의 대소문자를 뒤집고 커서를 앞으로 옮깁니다.[Count]_— 앞 명령의 Count번째 단어를 덧붙이고 입력 모드에 들어갑니다. Count를 생략하면 마지막 단어를 씁니다.*— 현재 단어에 별표(*)를 붙여 파일 이름 치환을 시도합니다. 일치하는 것이 없으면 벨을 울립니다. 있으면 단어를 일치 패턴으로 바꾸고 입력 모드에 들어갑니다.\— 파일 이름 완성. 현재 단어 뒤에 별표를 붙여 맞는 모든 파일 이름의 가장 긴 공통 접두사로 현재 단어를 바꿉니다. 일치가 하나뿐이면 디렉터리에는 슬래시/를, 디렉터리가 아니면 스페이스를 덧붙입니다.
기타 편집 명령
자주 쓰는 편집 명령은 다음과 같습니다.
[Count]yMotion,y[Count]Motion— 현재 문자부터 Motion이 지정한 커서 위치의 문자까지(포함) 끌어와(yank) 삭제 버퍼에 넣습니다. 텍스트와 커서는 바뀌지 않습니다.Y— 현재 위치부터 줄 끝까지 끌어옵니다.y$명령과 같습니다.u— 마지막 텍스트 수정 명령을 취소합니다.U— 줄에서 한 모든 텍스트 수정 명령을 취소합니다.[Count]v— 입력 버퍼에fc -e ${VISUAL:-${EDITOR:-vi}} Count명령을 돌려줍니다. Count를 생략하면 현재 줄을 씁니다.Ctrl-L— 줄을 바꾸고 현재 줄을 출력합니다. 제어 모드에서만 동작합니다.Ctrl-J— (줄 바꿈) 모드와 관계없이 현재 줄을 실행합니다.Ctrl-M— (Return) 모드와 관계없이 현재 줄을 실행합니다.#— 줄 앞에 샵 기호(#)를 넣은 뒤 줄을 보냅니다. 실행하지 않고 현재 줄을 기록에 넣고 싶을 때 쓸모 있습니다. 명령행에 파이프, 세미콜론, 줄 바꿈 문자가 있으면 각 기호 앞에도 샵 기호(#)를 넣습니다. 샵 기호를 모두 지우려면 기록에서 명령행을 가져와 샵 기호(#)를 한 번 더 입력합니다.=— 별표를 덧붙인 것처럼 현재 단어와 맞는 파일 이름을 나열합니다.@Letter— 별명 목록에서_Letter라는 별명을 찾아, 있으면 그 값을 처리할 입력 큐에 넣습니다.
Korn 셸이나 POSIX 셸 명령
Korn 셸은 대화식 명령 해석기이자 명령 프로그래밍 언어입니다. 운영 체제의 국제 표준인 POSIX(Portable Operating System Interface for Computer Environments)를 따릅니다.
POSIX는 운영 체제가 아니라 소스 수준에서 여러 시스템 사이의 응용 프로그램 이식성을 목표로 한 표준입니다. POSIX 기능은 Korn 셸 위에 만들어집니다. Korn 셸(POSIX 셸이라고도 함)은 입출력 방향 바꾸기, 변수 치환, 파일 이름 치환처럼 Bourne 셸과 C 셸의 기능을 많이 제공합니다. 또 다음과 같은 명령·프로그래밍 언어 기능을 더 갖추고 있습니다.
참고: rksh라는 Korn 셸의 제한판이 있습니다. 자세한 내용은 rksh 명령을 봅니다.
- 산술 평가 — Korn 셸(POSIX 셸)은 내장 let 명령으로 2진법부터 36진법까지 정수 산술을 할 수 있습니다. Korn 셸에서 0으로 시작하는 수(8진수)와 0x로 시작하는 수(16진수)를 인식하게 하려면 다음 명령을 실행합니다.
export XPG_SUS_ENV=ON—XPG_SUS_ENV변수를 내보내면 실행하는 명령과 그 명령이 쓰는 라이브러리가 완전히 POSIX를 따릅니다. 참고: 라이브러리 시스템 전체가 POSIX를 따르게 되므로 어떤 명령의 기본 동작이 바뀔 수 있습니다.export OCTAL_CONST=ON— 이 변수를 내보내면 Korn 셸에서 선언한 상수를 8진·16진 상수 인식 면에서 POSIX에 맞게 해석합니다.
- 명령 기록 — Korn 셸(POSIX 셸)은 입력한 모든 명령을 기록하는 파일을 둡니다. 텍스트 편집기로 이 기록 파일의 명령을 고쳐 다시 실행할 수 있습니다.
- 코프로세스 기능 — 프로그램을 백그라운드에서 실행하고 그 백그라운드 프로세스와 정보를 주고받을 수 있습니다.
- 편집 — Korn 셸(POSIX 셸)은 명령행을 편집할 수 있는 인라인 편집 옵션을 제공합니다. emacs, gmacs, vi와 비슷한 편집기를 쓸 수 있습니다.
Korn 셸 명령은 다음 가운데 하나입니다.
- 단순 명령
- 파이프라인
- 목록
- 복합 명령
- 함수
Korn 셸이나 POSIX 셸에서 명령을 내리면 셸은 명령을 평가해 다음을 합니다.
- 지정한 모든 치환을 합니다.
- 명령에 슬래시(
/)가 있는지 판단합니다. 있으면 지정한 경로 이름의 프로그램을 실행합니다.
명령에 슬래시(/)가 없으면 Korn 셸이나 POSIX 셸은 다음을 이어서 합니다.
- 명령이 특수 내장 명령인지 판단합니다. 그렇다면 현재 셸 프로세스 안에서 명령을 실행합니다.
- 명령을 사용자 정의 함수와 비교합니다. 사용자 정의 함수와 맞으면 위치 매개변수를 저장한 뒤 함수 호출의 인수로 다시 설정합니다. 함수가 끝나거나 return하면 위치 매개변수 목록을 되돌리고, 함수 안에서
EXIT에 설정한 trap을 실행합니다. 함수의 값은 마지막으로 실행한 명령의 값입니다. 함수는 현재 셸 프로세스에서 실행됩니다. - 명령 이름이 일반 내장 명령 이름과 맞으면 그 일반 내장 명령을 호출합니다.
- (명령이 내장 명령도 사용자 정의 함수도 아니면) 프로세스를 만들고 exec 명령으로 명령을 실행하려고 합니다.
Korn 셸(POSIX 셸)은 지정한 경로의 각 디렉터리에서 실행 파일을 찾습니다. PATH 셸 변수가 명령이 든 디렉터리의 검색 경로를 정합니다. 다른 디렉터리 이름은 콜론(:)으로 구분합니다. 기본 경로는 /usr/bin:(/usr/bin 디렉터리와 현재 디렉터리를 이 순서로 지정)입니다. 현재 디렉터리는 이웃한 콜론 둘 이상, 또는 경로 목록 처음이나 끝의 콜론으로 지정합니다.
파일에 실행 권한이 있지만 디렉터리나 a.out 파일이 아니면 셸은 셸 명령이 들어 있다고 봅니다. 현재 셸 프로세스는 서브셸을 만들어 파일을 읽습니다. 내보내지 않은 별명, 함수, 이름 있는 매개변수는 모두 지워집니다. 셸 명령 파일에 읽기 권한이 있거나(원문 그대로) setuid·setgid 비트가 설정돼 있으면, 셸은 권한을 설정하는 에이전트를 실행하고 셸 명령 파일을 열린 파일로 넘겨 셸을 실행합니다. 괄호로 감싼 명령은 내보내지 않은 것들을 지우지 않고 서브셸에서 실행됩니다.
관련 개념
- 제공되는 셸, 코프로세스 기능, Korn 셸 인라인 편집, Korn 셸 산술 평가, Korn 셸 내장 명령
Korn 셸 복합 명령
복합 명령은 단순 명령 목록이나 파이프라인일 수도 있고 예약어로 시작할 수도 있습니다. 셸 스크립트를 쓸 때는 대개 if, while, for 같은 복합 명령을 씁니다.
Korn 셸이나 POSIX 셸의 복합 명령은 다음과 같습니다.
for Identifier [in Word ...] ;do List ;done— for 명령을 실행할 때마다Identifier는 in Word ... 목록의 다음 단어로 설정됩니다. in Word ...를 생략하면 설정된 위치 매개변수마다 do List를 한 번씩 실행합니다. 목록에 단어가 더 없으면 실행이 끝납니다.select Identifier [in Word ...] ;do List ;done— select 명령은 지정한 단어 집합을 각각 번호를 붙여 표준 오류(파일 기술자 2)에 출력합니다. in Word ...를 생략하면 위치 매개변수를 대신 씁니다. PS3 프롬프트를 출력하고 표준 입력에서 한 줄을 읽습니다. 그 줄이 나열한 단어 가운데 하나의 번호이면 Identifier는 그 번호에 해당하는 단어로 설정됩니다. 표준 입력에서 읽은 줄이 비어 있으면 선택 목록을 다시 출력합니다. 그 밖에는 Identifier가 빈 값이 됩니다. 표준 입력에서 읽은 줄의 내용은REPLY매개변수에 저장됩니다. break나 파일 끝 문자를 만날 때까지 선택마다 List를 실행합니다.case Word in [[(] Pattern [| Pattern] ...) List ;;] ... esac— case 명령은 Word와 맞는 첫 Pattern에 연결된 List를 실행합니다. 패턴 형식은 파일 이름 치환에 쓰는 것과 같습니다.if List ;then List [elif List ;then List] ... [;else List] ;fi— List는 실행할 명령 목록입니다. 셸은 먼저 if List를 실행합니다. 종료 상태 0을 돌려주면 then List를 실행합니다. 아니면 elif 뒤의 List를 실행합니다. elif List의 마지막 명령이 0을 돌려주면 then List를 실행합니다. (원문 그대로) then List의 마지막 명령이 0을 돌려주면 else List를 실행합니다. else나 then에 대해 실행한 List 명령이 없으면 if 명령은 종료 상태 0을 돌려줍니다.while List ;do List ;done,until List ;do List ;done— List는 실행할 명령 목록입니다. while 명령은 List의 명령을 되풀이해 실행합니다. while List의 마지막 명령 종료 상태가 0이면 do List를 실행합니다. 0이 아니면 반복을 끝냅니다. do List의 명령을 하나도 실행하지 않으면 while 명령은 종료 상태 0을 돌려줍니다. until 명령은 while 명령 대신 써서 반복 종료 시험을 뒤집습니다.( List )— List는 실행할 명령 목록입니다. 셸은 List를 별도 환경에서 실행합니다. 참고: 중첩하려고 여는 괄호 두 개를 붙여 써야 하면, 명령과 산술 평가를 구분하도록 사이에 스페이스를 넣어야 합니다.{ List;}— List는 실행할 명령 목록입니다. List를 그대로 실행합니다. 참고: 메타 문자( )와 달리{ }는 예약어입니다(사용자 식별자가 아니라 특수 목적에 씀). 인식되려면 줄 처음이나 세미콜론(;) 뒤에 나와야 합니다.[[Expression]]— Expression을 평가합니다. 식이 참이면 종료 상태 0을 돌려줍니다.function Identifier { List ;},function Identifier () {List ;}— Identifier로 가리키는 함수를 정의합니다. 함수 본문은{ }로 감싼 지정한 명령 목록입니다.( )는 두 연산자로 이루어지므로 식별자와(,)사이에 공백을 섞어도 되지만 꼭 그럴 필요는 없습니다.time Pipeline— Pipeline을 실행합니다. 경과 시간, 사용자 시간, 시스템 시간을 표준 오류에 출력합니다.
관련 개념
- Korn 셸의 매개변수
셸 시작
ksh 명령, psh 명령(POSIX 셸), exec 명령으로 Korn 셸을 시작할 수 있습니다.
exec 명령으로 셸을 시작하고 인수 0($0)의 첫 문자가 하이픈(-)이면 로그인 셸로 봅니다. 셸은 먼저 /etc/profile 파일에서 명령을 읽고, 그다음 현재 디렉터리의 .profile 파일이나 $HOME/.profile 파일 가운데 있는 것에서 읽습니다. 다음으로 ENV 환경 변수 값에 매개변수 치환을 해서 얻은 이름의 파일이 있으면 거기서 명령을 읽습니다.
Korn 셸이나 POSIX 셸을 호출할 때 File [Parameter]를 지정하면 셸은 File로 지정한 스크립트 파일을 지정한 매개변수와 함께 실행합니다. 지정한 스크립트 파일에는 읽기 권한이 있어야 하며 setuid와 setgid 설정은 무시됩니다. 그런 다음 셸은 명령을 읽습니다.
참고: Korn 셸이나 POSIX 셸을 호출할 때 -c나 -s 플래그와 함께 스크립트 파일을 지정하지 않습니다.
위치 매개변수에 관한 자세한 내용은 Korn 셸의 매개변수를 봅니다.
Korn 셸 환경
명령이 실행을 시작할 때 아는 모든 변수(와 그 값)가 그 명령의 환경을 이룹니다.
이 환경에는 명령이 부모 프로세스에서 물려받은 변수와, 명령을 호출하는 명령행에서 키워드 매개변수로 지정한 변수가 들어 있습니다. 셸은 여러 방법으로 환경과 상호 작용합니다. 시작할 때 셸은 환경을 훑어 찾은 이름마다 매개변수를 만들고, 해당 값을 주고, 내보내기로 표시합니다. 실행한 명령은 환경을 물려받습니다.
export나 typeset -x 명령으로 셸 매개변수 값을 바꾸거나 새로 만들면 그 매개변수는 환경의 일부가 됩니다. 그래서 실행한 명령이 보는 환경은 셸이 원래 물려받은 이름-값 쌍(현재 셸이 값을 바꿨을 수 있음)에 export나 typeset -x 명령으로 더한 것을 합친 것입니다. 실행한 명령(서브셸)은 물려받은 환경 변수에 자기가 한 변경을 보지만, 그 자식 셸이나 프로세스가 바뀐 값을 보려면 서브셸이 그 변수를 내보내야 합니다.
단순 명령이나 함수의 환경은 앞에 매개변수 할당을 하나 이상 붙여 바꿉니다. 매개변수 할당 인수는 Identifier=Value 꼴의 단어입니다. 그래서 다음 두 식은 (명령 실행에 관한 한) 같습니다.
TERM=450 Command arguments
(export TERM; TERM=450; Command arguments)
Korn 셸 함수
function 예약어로 셸 함수를 정의합니다. 셸은 함수를 읽어 내부에 저장합니다. 별명 이름은 함수를 읽을 때 해석합니다. 셸은 함수를 명령과 같은 방식으로 실행하며 인수는 위치 매개변수로 넘깁니다.
Korn 셸이나 POSIX 셸은 함수를 호출한 환경에서 함수를 실행합니다. 다음은 함수와 호출한 스크립트가 공유하며 부작용이 생길 수 있습니다.
- 변수 값과 속성(함수 안에서 typeset 명령으로 지역 변수를 선언하지 않는 한)
- 작업 디렉터리
- 별명, 함수 정의, 속성
- 특수 매개변수
$ - 열린 파일
다음은 함수와 호출한 스크립트가 공유하지 않으며 부작용이 없습니다.
- 위치 매개변수
- 특수 매개변수
# - 함수를 호출할 때 변수 할당 목록에 든 변수
- 함수 안에서 typeset 명령으로 선언한 변수
- 옵션
- trap. 그러나 호출한 스크립트가 무시한 신호는 함수에서도 무시됩니다.
참고: 예전 Korn 셸에서는 EXIT와 ERR가 아닌 trap을 함수와 호출한 스크립트가 공유했습니다.
함수 본문 안에서 0이나 EXIT에 대한 trap을 실행하면, 함수가 끝난 뒤 함수를 호출한 환경에서 그 동작을 실행합니다. trap을 함수 본문 밖에서 실행하면 Korn 셸이 끝날 때 동작을 실행합니다. 예전 Korn 셸에서는 함수 본문 밖의 0이나 EXIT trap이 함수를 빠져나갈 때 실행되지 않았습니다.
함수를 실행할 때는 Korn 셸 내장 명령에서 설명한 것과 같은 구문 오류와 변수 할당 특성을 가집니다.
함수 이름을 단순 명령 이름으로 지정할 때마다 복합 명령이 실행됩니다. 명령의 피연산자는 복합 명령을 실행하는 동안 잠시 위치 매개변수가 됩니다. 특수 매개변수 #도 피연산자 수를 반영해 바뀝니다. 특수 매개변수 0은 바뀌지 않습니다.
return 특수 명령으로 함수 호출에서 돌아갑니다. 함수 안의 오류는 호출자에게 제어를 돌려줍니다.
함수 식별자는 typeset 특수 명령의 -f나 +f 옵션으로 나열합니다. -f 옵션은 함수 본문도 나열합니다. 함수는 unset 특수 명령의 -f 옵션으로 정의를 해제합니다.
보통 셸이 셸 스크립트를 실행하면 함수는 해제됩니다. typeset 특수 명령의 -xf 옵션을 쓰면 셸을 따로 호출하지 않고 실행하는 스크립트로 함수를 내보낼 수 있습니다. 셸을 따로 호출해도 정의돼 있어야 하는 함수는 ENV 파일에서 typeset 특수 명령의 -xf 옵션으로 지정해야 합니다.
함수 정의의 종료 상태는 함수 선언이 성공하지 않았으면 0이고(원문 그대로), 그렇지 않으면 0보다 큽니다. 함수 호출의 종료 상태는 함수가 가장 최근에 실행한 명령의 종료 상태입니다.
관련 개념
- Korn 셸의 매개변수, Korn 셸 내장 명령
Korn 셸이나 POSIX 셸의 명령 기록
Korn 셸이나 POSIX 셸은 터미널 장치에서 입력한 명령을 기록 파일에 저장합니다.
HISTFILE 변수가 설정돼 있으면 그 값이 기록 파일 이름입니다. HISTFILE 변수가 설정되지 않았거나 쓸 수 없으면 $HOME/.sh_history를 기록 파일로 씁니다. 기록 파일이 없고 Korn 셸이 만들 수 없거나, 있지만 Korn 셸에 덧붙일 권한이 없으면 Korn 셸은 임시 파일을 기록 파일로 씁니다. 셸은 알맞은 권한으로 같은 이름의 기록 파일을 쓰는 모든 대화식 셸의 명령에 접근합니다.
기본적으로 Korn 셸이나 POSIX 셸은 일반 사용자는 마지막 128개, root 사용자는 512개 명령의 텍스트를 저장합니다. 기록 파일 크기(HISTSIZE 변수로 지정)에는 제한이 없지만, 기록 파일이 아주 크면 Korn 셸이 느리게 시작할 수 있습니다.
명령 기록 치환
fc 내장 명령으로 기록 파일의 일부를 나열하거나 편집합니다. 편집하거나 나열할 부분을 고르려면 명령의 번호나 첫 글자(들)를 지정합니다.
명령 하나나 명령 범위를 지정할 수 있습니다.
fc 일반 내장 명령의 인수로 편집기 프로그램을 지정하지 않으면 FCEDIT 변수로 지정한 편집기를 씁니다. FCEDIT 변수가 정의되지 않았으면 /usr/bin/ed 파일을 씁니다. 편집한 명령은 편집기를 끝낼 때 출력되고 실행됩니다.
편집기 이름으로 하이픈(-)을 쓰면 편집 단계를 건너뛰고 명령을 다시 실행합니다. 이때 Old=New 꼴의 치환 매개변수로 실행 전에 명령을 고칠 수 있습니다. 예를 들어 r이 fc -e -의 별명이면 r bad=good c를 입력하면 문자 c로 시작하는 가장 최근 명령에서 첫 번째 bad 문자열을 good으로 바꿔 실행합니다.
관련 작업
- 이전에 입력한 명령 나열(history 명령)
Korn 셸이나 POSIX 셸의 명령 별명
Korn 셸(POSIX 셸)에서는 별명을 만들어 명령을 사용자에 맞게 바꿀 수 있습니다.
alias 명령은 Name=String 꼴의 단어를 별명으로 정의합니다. 별명을 명령행의 첫 단어로 쓰면 Korn 셸은 같은 이름의 별명을 이미 처리하고 있는지 확인합니다. 그렇다면 별명 이름을 바꾸지 않습니다. 같은 이름의 별명을 처리하고 있지 않으면 별명 이름을 별명 값으로 바꿉니다.
별명 이름의 첫 문자는 메타 문자를 뺀 출력 가능한 아무 문자나 될 수 있습니다. 나머지 문자는 올바른 식별자와 같은 규칙을 따라야 합니다. 바꿀 문자열에는 메타 문자를 포함해 올바른 셸 텍스트는 무엇이든 넣을 수 있습니다.
별명 값의 마지막 문자가 공백이면 셸은 별명 뒤의 단어도 별명 치환 대상인지 확인합니다. 별명으로 특수 내장 명령은 다시 정의할 수 있지만 예약어는 다시 정의할 수 없습니다. 별명 정의는 ksh를 호출할 때마다 물려받지 않습니다. 그러나 alias -x를 지정하면 별도 셸을 호출하지 않고 이름으로 호출한 스크립트에서도 별명이 유효합니다. 별명 정의를 내보내고 자식 프로세스가 쓸 수 있게 하려면 환경 파일에 alias -x와 별명 정의를 지정해야 합니다.
alias 명령으로 별명을 만들고 나열하고 내보냅니다.
unalias 명령으로 별명을 지웁니다.
별명을 만드는 형식은 다음과 같습니다.
alias Name=String
Name 매개변수는 별명 이름을, String 매개변수는 별명 값을 지정합니다.
다음 내보낸 별명은 Korn 셸이 미리 정의한 것이지만 해제하거나 다시 정의할 수 있습니다. 나중에 Korn 셸이 미리 정의한 대로 별명이 동작하리라 기대하는 사람을 헷갈리게 할 수 있으므로 바꾸지 않는 것이 좋습니다.
autoload=’typeset -fu’
false=’let 0’
functions=’typeset -f’
hash=’alias -t’
history=’fc -l’
integer=’typeset -i’
nohup=’nohup ’
r=’fc -e -’
true=’:’
type=’whence -v’
별명은 비대화식으로 호출한 Korn 셸(ksh)에서는 지원하지 않습니다. 예를 들어 셸 스크립트에서나, 다음처럼 ksh에 -c 옵션을 쓸 때입니다.
ksh -c alias
관련 작업
- 명령 별명 만들기(alias 셸 명령)
추적 별명
별명은 흔히 전체 경로 이름의 줄임으로 씁니다. 별명 기능의 한 옵션을 쓰면 별명 값을 해당 명령의 전체 경로 이름으로 자동 설정할 수 있습니다. 이런 특수한 별명을 추적 별명이라고 합니다.
추적 별명은 셸이 PATH 변수에서 전체 경로 이름을 찾을 필요를 없애 실행을 빠르게 합니다.
set -h 명령은 명령 추적을 켜서, 명령을 참조할 때마다 셸이 추적 별명 값을 정의하게 합니다. PATH 변수를 다시 설정할 때마다 이 값은 정의 해제됩니다.
이 별명은 추적 상태로 남아 있어 다음 참조 때 값을 다시 정의합니다. 몇몇 추적 별명은 셸에 컴파일돼 있습니다.
틸드 치환
셸은 별명 치환을 한 뒤 각 단어가 따옴표로 감싸지 않은 틸드(~)로 시작하는지 확인합니다. 그렇다면 단어의 첫 슬래시(/)까지가 /etc/passwd 파일의 사용자 이름과 맞는지 확인합니다. 맞는 것을 찾으면 ~ 문자와 이름을 그 사용자의 로그인 디렉터리로 바꿉니다. 이 과정을 틸드 치환이라고 합니다.
맞는 것을 찾지 못하면 원래 텍스트를 바꾸지 않습니다. Korn 셸은 ~ 문자가 단어의 유일한 문자이거나 뒤에 더하기 기호(+)나 하이픈(-)이 오면 다음과 같이 특별히 바꿉니다.
~— HOME 변수 값으로 바뀝니다.~+—$PWD변수(현재 디렉터리의 전체 경로 이름)로 바뀝니다.~-—$OLDPWD변수(이전 디렉터리의 전체 경로 이름)로 바뀝니다.
또 변수 할당 매개변수의 값이 틸드(~) 문자로 시작하면 셸은 틸드 치환을 시도합니다.
영어 원문
Job control in the Korn shell or POSIX shell
The Korn shell, or POSIX shell, provides a facility to control command sequences, or jobs.
When you execute the set -m special command, the Korn shell associates a job with each pipeline. It keeps a table of current jobs, printed by the jobs command, and assigns them small integer numbers.
When a job is started in the background with an ampersand (&), the shell prints a line that looks like the following:
[1] 1234
This output indicates that the job, which was started in the background, was job number 1. It also shows that the job had one (top-level) process with a process ID of 1234.
If you are running a job and want to do something else, use the Ctrl-Z key sequence. This key sequence sends a STOP signal to the current job. The shell normally indicates that the job has been stopped and then displays a shell prompt. You can then manipulate the state of this job (putting it in the background with the bg command), run other commands, and then eventually return the job to the foreground with the fg command. The Ctrl-Z key sequence takes effect immediately, and is like an interrupt in that the shell discards pending output and unread input when you type the sequence.
A job being run in the background stops if it tries to read from the terminal. Background jobs are normally allowed to produce output. You can disable this option by issuing the stty tostop command. If you set this terminal option, then background jobs stop when they try to produce output or read input.
You can refer to jobs in the Korn shell in several ways. A job is referenced by the process ID of any of its processes or in one of the following ways:
- %Number — Specifies the job with the given number.
- %String — Specifies any job whose command line begins with the String variable.
- %?String — Specifies any job whose command line contains the String variable.
- %% — Specifies the current job.
- %+ — Equivalent to
%%. - %- — Specifies the previous job.
This shell immediately recognizes changes in the process state. It normally informs you whenever a job becomes blocked so that no further progress is possible. The shell does this just before it prints a prompt so that it does not otherwise disturb your work.
When the monitor mode is on, each completed background job triggers traps set for the CHLD signal.
If you try to leave the shell (either by typing exit or using the Ctrl-D key sequence) while jobs are stopped or running, the system warns you with the message There are stopped (running) jobs. Use the jobs command to see which jobs are affected. If you immediately try to exit again, the shell terminates the stopped and running jobs without warning.
Signal handling:
The SIGINT and SIGQUIT signals for an invoked command are ignored if the command is followed by an ampersand (&) and the job monitor option is not active. Otherwise, signals have the values that the shell inherits from its parent.
When a signal for which a trap has been set is received while the shell is waiting for the completion of a foreground command, the trap associated with that signal will not be executed until after the foreground command has completed. Therefore, a trap on a CHILD signal is not performed until the foreground job terminates.
Inline editing in the Korn shell or POSIX shell
Normally, you type each command line from a terminal device and follow it by a newline character (RETURN or LINE FEED). When you activate the emacs, gmacs, or vi inline editing option, you can edit the command line.
The following commands enter edit modes:
- set -o emacs — Enters emacs editing mode and initiates an emacs-style inline editor.
- set -o gmacs — Enters emacs editing mode and initiates a gmacs-style inline editor.
- set -o vi — Enters vi editing mode and initiates a vi-style inline editor.
An editing option is automatically selected each time the VISUAL or EDITOR variable is assigned a value that ends in any of these option names.
Note: To use the editing features, your terminal must accept RETURN as a carriage return without line feed. A space must overwrite the current character on the screen.
Each editing mode opens a window at the current line. The window width is the value of the COLUMNS variable if it is defined; otherwise, the width is 80 character spaces. If the line is longer than the window width minus two, the system notifies you by displaying a mark at the end of the window. As the cursor moves and reaches the window boundaries, the window is centered about the cursor. The marks displayed are as follows:
>— Indicates that the line extends on the right side of the window.<— Indicates that the line extends on the left side of the window.*— Indicates that the line extends on both sides of the window.
The search commands in each edit mode provide access to the Korn shell history file. Only strings are matched. If the leading character in the string is a carat (^), the match must begin at the first character in the line.
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.
emacs editing mode:
The emacs editing mode is entered when you enable either the emacs or gmacs option. The only difference between these two modes is the way each handles the Ctrl-T edit command.
To edit, move the cursor to the point needing correction and insert or delete characters or words, as needed. All of the editing commands are control characters or escape sequences.
Edit commands operate from any place on a line (not only at the beginning). Do not press the Enter key or line-feed (Down Arrow) key after edit commands, except as noted.
- Ctrl-F — Moves the cursor forward (right) one character.
- Esc-F — Moves the cursor forward one word (a string of characters consisting of only letters, digits, and underscores).
- Ctrl-B — Moves the cursor backward (left) one character.
- Esc-B — Moves the cursor backward one word.
- Ctrl-A — Moves the cursor to the beginning of the line.
- Ctrl-E — Moves the cursor to the end of the line.
- Ctrl-] c — Moves the cursor forward on the current line to the indicated character.
- Esc-Ctrl-] c — Moves the cursor backward on the current line to the indicated character.
- Ctrl-X Ctrl-X — Interchanges the cursor and the mark.
- ERASE — Deletes the previous character. (User-defined erase character as defined by the stty command, usually the Ctrl-H key sequence.)
- Ctrl-D — Deletes the current character.
- Esc-D — Deletes the current word.
- Esc-Backspace — Deletes the previous word.
- Esc-H — Deletes the previous word.
- Esc-Delete — Deletes the previous word. If your interrupt character is the Delete key, this command does not work.
- Ctrl-T — Transposes the current character with the next character in emacs mode. Transposes the two previous characters in gmacs mode.
- Ctrl-C — Capitalizes the current character.
- Esc-C — Capitalizes the current word.
- Esc-L — Changes the current word to lowercase.
- Ctrl-K — Deletes from the cursor to the end of the line. If preceded by a numeric parameter whose value is less than the current cursor position, this editing command deletes from the given position up to the cursor. If preceded by a numeric parameter whose value is greater than the current cursor position, this editing command deletes from the cursor up to the given cursor position.
- Ctrl-W — Deletes from the cursor to the mark.
- Esc-P — Pushes the region from the cursor to the mark on the stack.
- KILL — User-defined kill character as defined by the stty command, usually the Ctrl-G key sequence or
@. Kills the entire current line. If two kill characters are entered in succession, all subsequent kill characters cause a line feed (useful when using paper terminals). - Ctrl-Y — Restores the last item removed from the line. (Yanks the item back to the line.)
- Ctrl-L — Line feeds and prints the current line.
- Ctrl-@ — (Null character) Sets a mark.
- Esc-space — Sets a mark.
- Ctrl-J — (New line) Executes the current line.
- Ctrl-M — (Return) Executes the current line.
- EOF — Processes the end-of-file character, normally the Ctrl-D key sequence, as an end-of-file only if the current line is null.
- Ctrl-P — Fetches the previous command. Each time the Ctrl-P key sequence is entered, the previous command back in time is accessed. Moves back one line when not on the first line of a multiple-line command.
Esc-<— Fetches the least recent (oldest) history line.- Esc-> — Fetches the most recent (youngest) history line.
- Ctrl-N — Fetches the next command line. Each time the Ctrl-N key sequence is entered, the next command line forward in time is accessed.
- Ctrl-R String — Reverses search history for a previous command line containing the string specified by the
Stringparameter. If a value of 0 is given, the search is forward. The specified string is terminated by an Enter or newline character. If the string is preceded by a carat (^), the matched line must begin with theStringparameter. If theStringparameter is omitted, then the next command line containing the most recentStringparameter is accessed. In this case, a value of 0 reverses the direction of the search. - Ctrl-O — (Operate) Executes the current line and fetches the next line relative to the current line from the history file.
- Esc Digits — (Escape) Defines the numeric parameter. The digits are taken as a parameter to the next command. The commands that accept a parameter are Ctrl-F, Ctrl-B, ERASE, Ctrl-C, Ctrl-D, Ctrl-K, Ctrl-R, Ctrl-P, Ctrl-N, Ctrl-], Esc-., Esc-Ctrl-],
Esc-_, Esc-B, Esc-C, Esc-D, Esc-F, Esc-H, Esc-L, and Esc-Ctrl-H. - Esc Letter — (Soft-key) Searches the alias list for an alias named
_Letter. If an alias of this name is defined, its value is placed into the input queue. The Letter parameter must not specify one of the escape functions. - Esc-[ Letter — (Soft-key) Searches the alias list for an alias named double underscore Letter (
__Letter). If an alias of this name is defined, its value is placed into the input queue. This command can be used to program function keys on many terminals. - Esc-. — Inserts on the line the last word of the previous command. If preceded by a numeric parameter, the value of this parameter determines which word to insert rather than the last word.
Esc-_— Same as the Esc-. key sequence.Esc-*— Attempts file name substitution on the current word. An asterisk (*) is appended if the word does not match any file or contain any special pattern characters.- Esc-Esc — File name completion. Replaces the current word with the longest common prefix of all file names that match the current word with an asterisk appended. If the match is unique, a slash (
/) is appended if the file is a directory and a space is appended if the file is not a directory. - Esc-= — Lists the files that match the current word pattern as if an asterisk (
*) were appended. - Ctrl-U — Multiplies the parameter of the next command by 4.
\— Escapes the next character. Editing characters and the ERASE, KILL and INTERRUPT (normally the Delete key) characters can be entered in a command line or in a search string if preceded by a backslash (\). The backslash removes the next character's editing features, if any.- Ctrl-V — Displays the version of the shell.
- Esc-# — Inserts a pound sign (
#) at the beginning of the line and then executes the line. This causes a comment to be inserted in the history file. - vi editing mode:
The vi editing mode has two typing modes.
The modes are:
Input mode. When you enter a command, the vi editor is in input mode.
Control mode. Press the Esc key to enter control mode.
Most control commands accept an optional repeat Count parameter prior to the command. When in vi mode on most systems, canonical processing is initially enabled. The command is echoed again if one or more of the following are true:
The speed is 1200 baud or greater.
The command contains any control characters.
Less than one second has elapsed since the prompt was printed.
The Esc character terminates canonical processing for the remainder of the command, and you can then modify the command line. This scheme has the advantages of canonical processing with the type-ahead echoing of raw mode. If the viraw option is also set, canonical processing is always disabled. This mode is implicit for systems that do not support two alternate end-of-line delimiters and might be helpful for certain terminals.
Available vi edit commands are grouped into categories. The categories are as follows:
Input edit commands:
The input edit commands for the Korn shell are described below.
Note: By default, the editor is in input mode.
- ERASE — Deletes the previous character. (User-defined erase character as defined by the stty command, usually Ctrl-H or
#.) - Ctrl-W — Deletes the previous blank separated word.
- Ctrl-D — Terminates the shell.
- Ctrl-V — Escapes the next character. Editing characters, such as the ERASE or KILL characters, can be entered in a command line or in a search string if preceded by a Ctrl-V key sequence. The Ctrl-V key sequence removes the next character's editing features (if any).
\— Escapes the next ERASE or KILL character.- Motion edit commands:
The motion edit commands for the Korn shell are described below.
Motion edit commands move the cursor as follows:
- [Count]l — Moves the cursor forward (right) one character.
- [Count]w — Moves the cursor forward one alphanumeric word.
- [Count]W — Moves the cursor to the beginning of the next word that follows a blank.
- [Count]e — Moves the cursor to the end of the current word.
- [Count]E — Moves the cursor to the end of the current blank-separated word.
- [Count]h — Moves the cursor backward (left) one character.
- [Count]b — Moves the cursor backward one word.
- [Count]B — Moves the cursor to the previous blank-separated word.
- [
Count]|— Moves the cursor to the column specified by the Count parameter. - [Count]fc — Finds the next character c in the current line.
- [Count]Fc — Finds the previous character c in the current line.
- [Count]tc — Equivalent to f followed by h.
- [Count]Tc — Equivalent to F followed by l.
- [Count]; — Repeats for the number of times specified by the Count parameter the last single-character find command: f, F, t, or T.
- [Count], — Reverses the last single-character find command the number of times specified by the Count parameter.
- 0 — Moves the cursor to the start of a line.
- ^ — Moves the cursor to the first nonblank character in a line.
$— Moves the cursor to the end of a line.- Search edit commands:
Search edit commands access your command history as follows:
- [Count]k — Fetches the previous command.
- [Count]
-— Equivalent to the k command. - [Count]j — Fetches the next command. Each time the j command is entered, the next command is accessed.
- [Count]
+— Equivalent to the j command. - [Count]G — Fetches the command whose number is specified by the Count parameter. The default is the least recent history command.
- /String — Searches backward through history for a previous command containing the specified string. The string is terminated by a RETURN or newline character. If the specified string is preceded by a carat (
^), the matched line must begin with the String parameter. If the value of the String parameter is null, the previous string is used. - ?String — Same as /String except that the search is in the forward direction.
- n — Searches for the next match of the last pattern to /String or ? commands.
- N — Searches for the next match of the last pattern to /String or ? commands, but in the opposite direction. Searches history for the string entered by the previous /String command.
- Text modification edit commands:
Text-modification edit commands modify the line as follows:
- a — Enters the input mode and enters text after the current character.
- A — Appends text to the end of the line. Equivalent to the
$acommand.
[Count]cMotion c[Count]Motion Deletes the current character through the character to which the Motion parameter specifies to move the cursor, and enters input mode. If the value of the Motion parameter is c, the entire line is deleted and the input mode is entered.
C Deletes the current character through the end of the line and enters input mode. Equivalent to the c$ command.
S Equivalent to the cc command.
D Deletes the current character through the end of line. Equivalent to the d$ command.
- [Count]dMotion d[Count]Motion — Deletes the current character up to and including the character specified by the Motion parameter. If Motion is d, the entire line is deleted.
- i — Enters the input mode and inserts text before the current character.
- I — Inserts text before the beginning of the line. Equivalent to the 0i command.
- [Count]P — Places the previous text modification before the cursor.
- [Count]p — Places the previous text modification after the cursor.
- R — Enters the input mode and types over the characters on the screen.
- [Count]rc — Replaces the number of characters specified by the Count parameter, starting at the current cursor position, with the characters specified by the c parameter. This command also advances the cursor after the characters are replaced.
- [Count]x — Deletes the current character.
- [Count]X — Deletes the preceding character.
- [Count]. — Repeats the previous text-modification command.
- [Count]~ — Inverts the case of the number of characters specified by the Count parameter, starting at the current cursor position, and advances the cursor.
- [
Count]_— Appends the word specified by the Count parameter of the previous command and enters input mode. The last word is used if the Count parameter is omitted. *— Appends an asterisk (*) to the current word and attempts file name substitution. If no match is found, it rings the bell. Otherwise, the word is replaced by the matching pattern and input mode is entered.\— File name completion. Replaces the current word with the longest common prefix of all file names matching the current word with an asterisk (*) appended. If the match is unique, a slash/is appended if the file is a directory. A space is appended if the file is not a directory.- Miscellaneous edit commands:
The most commonly used edit commands follow:
- [Count]yMotion
- y[Count]Motion — Yanks the current character up to and including the character marked by the cursor position specified by the Motion parameter and puts all of these characters into the delete buffer. The text and cursor are unchanged.
- Y — Yanks from the current position to the end of the line. Equivalent to the
y$command. - u — Undoes the last text-modifying command.
- U — Undoes all the text-modifying commands performed on the line.
- [Count]v — Returns the command
fc -e ${VISUAL:-${EDITOR:-vi}}Count in the input buffer. If the Count parameter is omitted, then the current line is used. - Ctrl-L — Line feeds and prints the current line. This command is effective only in control mode.
- Ctrl-J — (New line) Executes the current line regardless of the mode.
- Ctrl-M — (Return) Executes the current line regardless of the mode.
#— Sends the line after inserting a pound sign (#) in front of the line. Useful if you want to insert the current line in the history without executing it. If the command line contains a pipe or semicolon or newline character, then additional pound signs (#) will be inserted in front of each of these symbols. To delete all pound signs, retrieve the command line from history and enter another pound sign (#).- = — Lists the file names that match the current word as if an asterisk were appended to it.
- @Letter — Searches the alias list for an alias named
_Letter. If an alias of this name is defined, its value is placed into the input queue for processing.
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.
POSIX is not an operating system, but is a standard aimed at portability of applications, at the source level, across many systems. POSIX features are built on top of the Korn shell. The Korn shell (also known as the POSIX shell) offers many of the same features as the Bourne and C shells, such as I/O redirection capabilities, variable substitution, and file name substitution. It also includes several additional command and programming language features:
Note: There is a restricted version of Korn shell available, called rksh. For more details, refer to the rksh command.
- Arithmetic evaluation — The Korn shell, or POSIX shell, can perform integer arithmetic using the built-in let command, using any base from 2 to 36. In order to enable recognition of numbers starting with 0 (Octal) and 0x (Hexadecimal) in the Korn shell, run the following commands: export
XPG_SUS_ENV=ONExporting theXPG_SUS_ENVvariable causes the commands that are run and the libraries that they use to be completely POSIX-compliant. Note: Because the entire library system becomes POSIX-compliant, a given command's default expected behavior might change. exportOCTAL_CONST=ONExporting this variable causes the interpretation of constants declared in the Korn shell to be POSIX-compliant as far as the recognition of octal and hexadecimal constants is concerned. - Command history — The Korn shell, or POSIX shell, stores a file that records all of the commands you enter. You can use a text editor to alter a command in this history file and then reissue the command.
- Coprocess facility — Enables you to run programs in the background and send and receive information to these background processes.
- Editing — The Korn shell, or POSIX shell, offers inline editing options that enable you to edit the command line. Editors similar to emacs, gmacs, and vi are available.
A Korn shell command is one of the following:
Simple command
Pipeline
List
Compound command
Function
When you issue a command in the Korn shell or POSIX shell, the shell evaluates the command and does the following:
Makes all indicated substitutions.
Determines whether the command contains a slash (
/). If it does, the shell runs the program named by the specified path name.
If the command does not contain a slash (/), the Korn shell or POSIX shell continues with the following actions:
Determines whether the command is a special built-in command. If it is, the shell runs the command within the current shell process.
Compares the command to user-defined functions. If the command matches a user-defined function, then the positional parameters are saved and then reset to the arguments of the function call. When the function completes or issues a return, the positional parameter list is restored, and any trap set on
EXITwithin the function is carried out. The value of a function is the value of the last command executed. A function is carried out in the current shell process.If the command name matches the name of a regular built-in command, then that regular built-in command will be invoked.
Creates a process and attempts to carry out the command by using the exec command (if the command is neither a built-in command nor a user-defined function).
The Korn shell, or POSIX shell, searches each directory in a specified path for an executable file. The PATH shell variable defines the search path for the directory containing the command. Alternative directory names are separated with a colon (:). The default path is /usr/bin: (specifying the /usr/bin directory, and the current directory, in that order). The current directory is specified by two or more adjacent colons, or by a colon at the beginning or end of the path list.
If the file has execute permission but is not a directory or an a.out file, the shell assumes that it contains shell commands. The current shell process creates a subshell to read the file. All nonexported aliases, functions, and named parameters are removed from the file. If the shell command file has read permission, or if the setuid or setgid bits are set on the file, then the shell runs an agent that sets up the permissions and carries out the shell with the shell command file passed down as an open file. A parenthesized command is run in a subshell without removing nonexported quantities.
Related concepts
Available shells The following are the shells that are provided with AIX. 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. Inline editing in the Korn shell or POSIX shell Normally, you type each command line from a terminal device and follow it by a newline character (RETURN or LINE FEED). When you activate the emacs, gmacs, or vi inline editing option, you can edit the command line. 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. 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.
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.
The following is a list of list of Korn shell or POSIX shell compound commands:
- for Identifier [in Word ...] ;do List ;done — Each time a for command is executed, the
Identifierparameter is set to the next word taken from the in Word ... list. If the in Word ... command is omitted, then the for command executes the do List command once for each positional parameter that is set. Execution ends when there are no more words in the list. - select Identifier [in Word ...] ;do List ;done — A select command prints on standard error (file descriptor 2) the set of words specified, each preceded by a number. If the in Word ... command is omitted, then the positional parameters are used instead. The PS3 prompt is printed and a line is read from the standard input. If this line consists of the number of one of the listed words, then the value of the Identifier parameter is set to the word corresponding to this number. If the line read from standard input is empty, the selection list is printed again. Otherwise, the value of the Identifier parameter is set to null. The contents of the line read from standard input is saved in the
REPLYparameter. The List parameter is executed for each selection until a break or an end-of-file character is encountered. - case Word in [[ ( ] Pattern [
|Pattern] ... ) List ;;] ... esac — A case command executes the List parameter associated with the first Pattern parameter that matches the Word parameter. The form of the patterns is the same as that used for file name substitution. - if List ;then List [elif List ;then List] ... [;else List] ;fi — The List parameter specifies a list of commands to be run. The shell executes the if List command first. If a zero exit status is returned, it executes the then List command. Otherwise, the commands specified by the List parameter following the elif command are executed. If the value returned by the last command in the elif List command is zero, the then List command is executed. If the value returned by the last command in the then List command is zero, the else List command is executed. If no commands specified by the List parameters are executed for the else or then command, the if command returns a zero exit status.
- while List ;do List ;done until List ;do List ;done — The List parameter specifies a list of commands to be run. The while command repeatedly executes the commands specified by the List parameter. If the exit status of the last command in the while List command is zero, the do List command is executed. If the exit status of the last command in the while List command is not zero, the loop terminates. If no commands in the do List command are executed, then the while command returns a zero exit status. The until command might be used in place of the while command to negate the loop termination test.
- ( List) — The List parameter specifies a list of commands to run. The shell executes the List parameter in a separate environment. Note: If two adjacent open parentheses are needed for nesting, you must insert a space between them to differentiate between the command and arithmetic evaluation.
- { List;} — The List parameter specifies a list of commands to run. The List parameter is simply executed. Note: Unlike the metacharacters
( ),{ }denote reserved words (used for special purposes, not as user-declared identifiers). To be recognized, these reserved words must appear at the beginning of a line or after a semicolon (;). - [[Expression]] — Evaluates the Expression parameter. If the expression is true, then the command returns a zero exit status.
- function Identifier { List ;} or function Identifier () {List ;} — Defines a function that is referred to by the Identifier parameter. The body of the function is the specified list of commands enclosed by
{ }. The( )consists of two operators, so mixing blank characters with the identifier,(and)is permitted, but is not necessary. - time Pipeline — Executes the Pipeline parameter. The elapsed time, user time, and system time are printed to standard error.
Related concepts
Parameters in the Korn shell Korn shell parameters are discussed below.
Shell startup:
You can start the Korn shell with the ksh command, psh command (POSIX shell), or the exec command.
If the shell is started by the exec command, and the first character of zero argument ($0) is the hyphen (-), then the shell is assumed to be a login shell. The shell first reads commands from the /etc/profile file and then from either the .profile file in the current directory or from the $HOME/.profile file, if either file exists. Next, the shell reads commands from the file named by performing parameter substitution on the value of the ENV environment variable, if the file exists.
If you specify the File [Parameter] parameter when invoking the Korn shell or POSIX shell, 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 are ignored. The shell then reads the commands.
Note: Do not specify a script file with the -c or -s flags when invoking the Korn shell or POSIX shell.
For more information on positional parameters, see Parameters in the Korn shell.
Related concepts
Parameters in the Korn shell Korn shell parameters are discussed below.
Korn shell environment:
All variables (with their associated values) known to a command at the beginning of its execution constitute its environment.
This environment includes variables that a command inherits from its parent process and variables specified as keyword parameters on the command line that calls the command. The shell interacts with the environment in several ways. When it is started, the shell scans the environment and creates a parameter for each name found, giving the parameter the corresponding value and marking it for export. Executed commands inherit the environment.
If you modify the values of the shell parameters or create new ones using the export or typeset -x commands, the parameters become part of the environment. The environment seen by any executed command is therefore composed of any name-value pairs originally inherited by the shell, whose values might be modified by the current shell, plus any additions that resulted from using the export or typeset -x commands. The executed command (subshell) will see any modifications it makes to the environment variables it has inherited, but for its child shells or processes to see the modified values, the subshell must export these variables.
The environment for any simple command or function is changed by prefixing with one or more parameter assignments. A parameter assignment argument is a word of the form Identifier=Value. Thus, the two following expressions are equivalent (as far as the execution of the command is concerned):
TERM=450 Command arguments
(export TERM; TERM=450; Command arguments)
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.
The Korn shell or POSIX shell executes functions in the environment from which functions are invoked. All of the following are shared by the function and the invoking script, and side effects can be produced:
Variable values and attributes (unless you use typeset command within the function to declare a local variable)
Working directory
Aliases, function definitions, and attributes
Special parameter
$Open files
The following are not shared between the function and the invoking script, and there are no side effects:
Positional parameters
Special parameter
#Variables in a variable assignment list when the function is invoked
Variables declared using typeset command within the function
Options
Traps. However, signals ignored by the invoking script will also be ignored by the function.
Note: In earlier versions of the Korn shell, traps other than EXIT and ERR were shared by the function as well as the invoking script.
If trap on 0 or EXIT is executed inside the body of a function, then the action is executed after the function completes, in the environment that called the function. If the trap is executed outside the body of a function, then the action is executed upon exit from the Korn shell. In earlier versions of the Korn shell, no trap on 0 or EXIT outside the body of a function was executed upon exit from the function.
When a function is executed, it has the same syntax-error and variable-assignment properties described in Korn shell or POSIX shell built-in commands.
The compound command is executed whenever the function name is specified as the name of a simple command. The operands to the command temporarily will become the positional parameters during the execution of the compound command. The special parameter # will also change to reflect the number of operands. The special parameter 0 will not change.
The return special command is used to return from function calls. Errors within functions return control to the caller.
Function identifiers are listed with the -f or +f option of the typeset special command. The -f option also lists the text of functions. Functions are undefined with the -f option of the unset special command.
Ordinarily, functions are unset when the shell executes a shell script. The -xf option of the typeset special command allows a function to be exported to scripts that are executed without a separate invocation of the shell. Functions that must be defined across separate invocations of the shell should be specified in the ENV file with the -xf option of the typeset special command.
The exit status of a function definition is zero if the function was not successfully declared. Otherwise, it will be greater than zero. The exit status of a function invocation is the exit status of the most recent command executed by the function.
Related concepts
Parameters in the Korn shell Korn shell parameters are discussed below. 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.
Korn shell or POSIX shell command history:
The Korn shell or POSIX shell saves commands entered from your terminal device to a history file.
If set, the HISTFILE variable value is the name of the history file. If the HISTFILE variable is not set or cannot be written, the history file used is $HOME/.sh_history. If the history file does not exist and the Korn shell cannot create it, or if it does exist and the Korn shell does not have permission to append to it, then the Korn shell uses a temporary file as the history file. The shell accesses the commands of all interactive shells using the same named history file with appropriate permissions.
By default, the Korn shell or POSIX shell saves the text of the last 128 commands for nonroot users and 512 commands for the root user. The history file size (specified by the HISTSIZE variable) is not limited, although a very large history file can cause the Korn shell to start slowly.
Command history substitution:
Use the fc built-in command to list or edit portions of the history file. To select a portion of the file to edit or list, specify the number or the first character or characters of the command.
You can specify a single command or range of commands.
If you do not specify an editor program as an argument to the fc regular built-in command, the editor specified by the FCEDIT variable is used. If the FCEDIT variable is not defined, then the /usr/bin/ed file is used. The edited command or commands are printed and run when you exit the editor.
The editor name hyphen (-) is used to skip the editing phase and run the command again. In this case, a substitution parameter of the form Old=New can be used to modify the command before it is run. For example, if r is aliased to fc -e -, then typing r bad=good c runs the most recent command that starts with the letter c and replaces the first occurrence of the bad string with the good string.
Related tasks
Listing previously entered commands (history command) Use the history command to list commands that you have previously entered.
Command aliasing in the Korn shell or POSIX shell
The Korn shell, or POSIX shell, allows you to create aliases to customize commands.
The alias command defines a word of the form Name=String as an alias. When you use an alias as the first word of a command line, the Korn shell checks to see if it is already processing an alias with the same name. If it is, the Korn shell does not replace the alias name. If an alias with the same name is not already being processed, the Korn shell replaces the alias name by the value of the alias.
The first character of an alias name can be any printable character except the metacharacters. The remaining characters must be the same as for a valid identifier. The replacement string can contain any valid shell text, including the metacharacters.
If the last character of the alias value is a blank, the shell also checks the word following the alias for alias substitution. You can use aliases to redefine special built-in commands but not to redefine reserved words. Alias definitions are not inherited across invocations of ksh. However, if you specify alias -x, the alias stays in effect for scripts invoked by name that do not invoke a separate shell. To export an alias definition and to cause child processes to have access to them, you must specify alias -x and the alias definition in your environment file.
Use the alias command to create, list, and export aliases.
Use the unalias command to remove aliases.
The format for creating an alias is as follows:
alias Name=String
where the Name parameter specifies the name of the alias, and the String parameter specifies the value of the alias.
The following exported aliases are predefined by the Korn shell but can be unset or redefined. It is not recommended that you change them, because this might later confuse anyone who expects the alias to work as predefined by the Korn shell.
autoload=’typeset -fu’
false=’let 0’
functions=’typeset -f’
hash=’alias -t’
history=’fc -l’
integer=’typeset -i’
nohup=’nohup ’
r=’fc -e -’
true=’:’
type=’whence -v’
Aliases are not supported on noninteractive invocations of the Korn shell (ksh); for example, in a shell script, or with the -c option in ksh, as in the following:
ksh -c alias
Related tasks
Creating a command alias (alias shell command) An alias lets you create a shortcut name for a command, file name, or any shell text. By using aliases, you save a lot of time when doing tasks you do frequently. You can create a command alias.
Tracked aliases:
Frequently, aliases are used as shorthand for full path names. One aliasing facility option allows you to automatically set the value of an alias to the full path name of a corresponding command. This special type of alias is a tracked alias.
Tracked aliases speed execution by eliminating the need for the shell to search the PATH variable for a full path name.
The set -h command turns on command tracking so that each time a command is referenced, the shell defines the value of a tracked alias. This value is undefined each time you reset the PATH variable.
These aliases remain tracked so that the next subsequent reference will redefine the value. Several tracked aliases are compiled into the shell.
Tilde substitution:
After the shell performs alias substitution, it checks each word to see if it begins with an unquoted tilde (~). If it does, the shell checks the word, up to the first slash (/), to see if it matches a user name in the /etc/passwd file. If the shell finds a match, it replaces the ~ character and the name with the login directory of the matched user. This process is called tilde substitution.
The shell does not change the original text if it does not find a match. The Korn shell also makes special replacements if the ~ character is the only character in the word or followed by plus sign (+) or hyphen (-):
~— Replaced by the value of the HOME variable~+— Replaced by the$PWDvariable (the full path name of the current directory)~-— Replaced by the$OLDPWDvariable (the full path name of the previous directory)
In addition, the shell attempts tilde substitution when the value of a variable assignment parameter begins with a tilde ~ character.