[AIX 운영 체제와 장치 관리 19] 파일과 디렉터리 링크, DOS 파일, 파일 명령 요약, 운영 체제 셸과 셸 개념

핵심 정리

  • 디렉터리 항목은 모두 파일 이름과 i-node 번호를 잇는 링크입니다. 하드 링크는 같은 파일 시스템 안에서만 만들 수 있고 마지막 하드 링크가 지워져야 데이터가 사라집니다. 심볼릭 링크(ln -s)는 경로를 담은 특수 파일로 다른 파일 시스템도 가리키지만 삭제를 막지 못합니다.
  • DOS 파일 명령은 DOS 경로 구분자로 백슬래시 대신 슬래시를 쓰며, *·? 와일드카드가 제대로 동작하지 않습니다. -a는 텍스트 변환, -D는 장치 지정입니다.
  • AIX 6.1의 기본 셸(/usr/bin/sh)은 Korn 셸입니다. Bourne·제한·POSIX·C·신뢰·원격 셸과 ksh·ksh93의 제한판 rksh·rksh93이 함께 제공됩니다.
  • 스크립트 첫 줄 #!경로로 실행할 셸을 정하지만, ksh myfile처럼 명령행에서 셸을 주면 그것이 우선합니다.
  • 제한 셸(Rsh, bsh -r, ksh -r)은 cd, PATH·SHELL 변경, 슬래시가 든 경로, 출력 방향 바꾸기를 막고, .profile을 해석한 뒤 제한을 겁니다.
항목 내용
버전 AIX 6.1 (5.3판과 거의 같음, 셸 설명 일부 바뀜)
원문 Operating system and device management — 5.3판 356360쪽·394403쪽, 6.1판 194~205쪽
관련 명령어 ln, rm, dosread, doswrite, dosdel, dosdir, ksh, bsh, Rsh, psh, csh, tsh, rksh, chmod, recsh
관련 파일 /etc/passwd, /usr/bin/sh, /usr/bin/ksh, /usr/bin/bsh, $HOME/.profile, /usr/rbin

링크는 파일 이름과 파일의 내부 표현인 색인 노드 참조 번호(i-node 번호)를 잇는 연결입니다. 디렉터리 항목은 파일 이름과 i-node 번호의 쌍이므로 모든 디렉터리 항목은 링크입니다.

실제로 파일을 식별하는 것은 파일 이름이 아니라 i-node 번호입니다. 링크를 쓰면 어떤 i-node 번호나 파일이든 여러 이름으로 알려질 수 있습니다. 예를 들어 i-node 번호 798에 Omaha 사무소의 6월 판매에 관한 메모가 들어 있다고 합시다. 지금 이 메모의 디렉터리 항목은 다음과 같습니다.

i-node 번호 파일 이름
798 memo

이 정보는 sales와 omaha 디렉터리에 저장된 정보와 관련 있으므로, 필요한 곳에서 정보를 공유하려고 링크를 씁니다. ln 명령으로 이 디렉터리들에 링크를 만듭니다. 이제 파일 이름은 다음 세 개입니다.

i-node 번호 파일 이름
798 memo
798 sales/june
798 omaha/junesales

pg나 cat 명령으로 세 파일 이름 가운데 어느 것의 내용을 봐도 같은 정보가 나옵니다. 세 이름 가운데 어느 것으로든 i-node 번호의 내용을 편집하면 모든 파일 이름이 보여 주는 데이터에 그 변경이 반영됩니다.

링크 종류

링크에는 하드 링크와 심볼릭 링크 두 종류가 있습니다.

링크는 ln 명령으로 만들며 종류는 다음과 같습니다.

종류 설명
하드 링크 새 파일 이름으로 파일 데이터에 접근하게 합니다. 하드 링크는 파일이 존재하도록 보장합니다. 마지막 하드 링크를 지우면 i-node 번호와 그 데이터가 지워집니다. 하드 링크는 같은 파일 시스템에 있는 파일 사이에서만 만들 수 있습니다.
심볼릭 링크 새 파일 이름으로 다른 파일 시스템의 데이터에 접근하게 합니다. 심볼릭 링크는 경로 이름을 담은 특수한 종류의 파일입니다. 프로세스가 심볼릭 링크를 만나면 그 경로를 찾아갈 수 있습니다. 심볼릭 링크는 파일 시스템에서 파일이 지워지는 것을 막지 못합니다.

참고: 파일을 만든 사용자는 링크가 몇 개 만들어지든 그 파일의 소유권을 유지합니다.

파일 소유자나 root 사용자만 그 파일의 접근 모드를 설정할 수 있습니다. 그러나 알맞은 접근 모드가 있으면 링크된 파일 이름으로 파일을 바꿀 수 있습니다.

파일이나 디렉터리는 그 i-node 번호에 대한 하드 링크가 하나라도 있으면 존재합니다. ls -l 명령의 긴 목록에는 각 파일과 하위 디렉터리의 하드 링크 수가 나옵니다. 운영 체제는 어느 링크가 먼저 만들어졌든 모든 하드 링크를 똑같이 취급합니다.

파일 링크(ln 명령)

ln 명령으로 파일을 링크하면 같은 데이터를 여러 곳에 있는 것처럼 편하게 다룰 수 있습니다.

링크는 원래 파일에 다른 이름을 붙여 만듭니다. 링크를 쓰면 데이터베이스나 메일 목록 같은 큰 파일을 사본을 만들지 않고 여러 사용자가 공유할 수 있습니다. 링크는 디스크 공간을 아낄 뿐 아니라 한 파일에 한 변경이 링크된 모든 파일에 자동으로 반영됩니다.

ln 명령은 SourceFile 매개변수로 지정한 파일을 TargetFile 매개변수로 지정한 파일, 또는 TargetDirectory 매개변수로 지정한 다른 디렉터리의 같은 파일 이름에 링크합니다. 기본적으로 ln 명령은 하드 링크를 만듭니다. 심볼릭 링크를 만들려면 -s 플래그를 더합니다.

참고: -s 플래그 없이는 파일 시스템을 넘어 파일을 링크할 수 없습니다.

파일을 새 이름에 링크할 때는 파일을 하나만 나열할 수 있습니다. 디렉터리에 링크할 때는 파일을 여러 개 나열할 수 있습니다.

TargetFile 매개변수는 선택입니다. 대상 파일을 지정하지 않으면 ln 명령은 현재 디렉터리에 파일을 만듭니다. 새 파일은 SourceFile 매개변수로 지정한 파일의 이름을 물려받습니다.

다음 예를 봅니다.

  • chap1이라는 파일의 링크를 만들려면 다음을 입력합니다.
text
ln -f chap1 intro

chap1을 새 이름 intro에 링크합니다. -f 플래그를 쓰면 intro라는 파일 이름이 없을 때 만들어집니다. intro가 있으면 그 파일은 chap1에 대한 링크로 바뀝니다. chap1과 intro 두 파일 이름 모두 같은 파일을 가리킵니다.

  • index라는 파일을 manual이라는 다른 디렉터리의 같은 이름에 링크하려면 다음을 입력합니다.
text
ln index manual

index를 새 이름 manual/index에 링크합니다.

  • 여러 파일을 다른 디렉터리의 이름에 링크하려면 다음을 입력합니다.
text
ln chap2 jim/chap3 /home/manual

chap2를 새 이름 /home/manual/chap2에, jim/chap3을 /home/manual/chap3에 링크합니다.

  • 패턴 일치 문자와 함께 ln 명령을 쓰려면 다음을 입력합니다.
text
ln manual/* .

참고: 별표와 마침표 사이에 공백을 꼭 넣어야 합니다. manual 디렉터리의 모든 파일을 현재 디렉터리(점 .)에 manual 디렉터리에서와 같은 이름으로 링크합니다.

  • 심볼릭 링크를 만들려면 다음을 입력합니다.
text
ln -s /tmp/toc toc

현재 디렉터리에 심볼릭 링크 toc를 만듭니다. toc 파일은 /tmp/toc 파일을 가리킵니다. /tmp/toc 파일이 있으면 cat toc 명령이 그 내용을 나열합니다.

  • TargetFile 매개변수를 지정하지 않고 같은 결과를 얻으려면 다음을 입력합니다.
text
ln -s /tmp/toc

전체 구문은 Commands Reference, Volume 3의 ln 명령을 봅니다.

링크된 파일을 지우는 명령

rm 명령은 지정한 파일 이름에서 링크를 지웁니다.

하드 링크된 여러 파일 이름 가운데 하나를 지우면 파일은 다른 이름으로 남아 있으므로 완전히 지워지지 않습니다. i-node 번호에 대한 마지막 링크를 지우면 데이터도 지워집니다. 그러면 시스템이 그 i-node 번호를 다시 쓸 수 있습니다.

전체 구문은 Commands Reference, Volume 3의 rm 명령을 봅니다.

영어 원문

File and directory links

Links are connections between a file name and an index node reference number (i-node number), the internal representation of a file. Because directory entries contain file names paired with i-node numbers, every directory entry is a link.

The i-node number actually identifies the file, not the file name. By using links, any i-node number or file can be known by many different names. For example, i-node number 798 contains a memo regarding June sales in the Omaha office. Presently, the directory entry for this memo is as follows:

  • 798 — memo

Because this information relates to information stored in the sales and omaha directories, linking is used to share the information where it is needed. Using the ln command, links are created to these directories. Now the file has three file names as follows:

  • 798 — memo
  • 798 — sales/june
  • 798 — omaha/junesales

When you use the pg or cat command to view the contents of any of the three file names, the same information is displayed. If you edit the contents of the i-node number from any of the three file names, the contents of the data displayed by all of the file names will reflect any changes.

Types of links

There are two types of links: hard and symbolic.

Links are created with the ln command and are of the following types:

  • hard link — Allows access to the data of a file from a new file name. Hard links ensure the existence of a file. When the last hard link is removed, the i-node number and its data are deleted. Hard links can be created only between files that are in the same file system.
  • symbolic link — Allows access to data in other file systems from a new file name. The symbolic link is a special type of file that contains a path name. When a process encounters a symbolic link, the process may search that path. Symbolic links do not protect a file from deletion from the file system.
  • Note: The user who creates a file retains ownership of that file no matter how many links are created.

Only the owner of the file or the root user can set the access mode for that file. However, changes can be made to the file from a linked file name with the proper access mode.

A file or directory exists as long as there is one hard link to the i-node number for that file. In the long listing displayed by the ls -l command, the number of hard links to each file and subdirectory is given. All hard links are treated equally by the operating system, regardless of which link was created first.

Linking files (ln command)

Linking files with the ln command is a convenient way to work with the same data as if it were in more than one place.

Links are created by giving alternate names to the original file. The use of links allows a large file, such as a database or mailing list, to be shared by several users without making copies of that file. Not only do links save disk space, but changes made to one file are automatically reflected in all the linked files.

The ln command links the file designated in the SourceFile parameter to the file designated by the TargetFile parameter or to the same file name in another directory specified by the TargetDirectory parameter. By default, the ln command creates hard links. To use the ln command to create symbolic links, add the -s flag.

Note: You cannot link files across file systems without using the -s flag.

If you are linking a file to a new name, you can list only one file. If you are linking to a directory, you can list more than one file.

The TargetFile parameter is optional. If you do not designate a target file, the ln command creates a file in your current directory. The new file inherits the name of the file designated in the SourceFile parameter.

See the following examples:

  • To create a link to a file named chap1, type the following:
text
ln -f chap1 intro

This links chap1 to the new name, intro. When the -f flag is used, the file name intro is created if it does not already exist. If intro does exist, the file is replaced by a link to chap1. Both the chap1 and intro file names refer to the same file.

  • To link a file named index to the same name in another directory named manual, type the following:
text
ln index manual

This links index to the new name, manual/index.

  • To link several files to names in another directory, type the following:
text
ln chap2 jim/chap3 /home/manual

This links chap2 to the new name /home/manual/chap2 and jim/chap3 to /home/manual/chap3.

  • To use the ln command with pattern-matching characters, type the following:
text
ln manual/* .

Note: You must type a space between the asterisk and the period. This links all files in the manual directory into the current directory, dot (.), giving them the same names they have in the manual directory.

  • To create a symbolic link, type the following:
text
ln -s /tmp/toc toc

This creates the symbolic link, toc, in the current directory. The toc file points to the /tmp/toc file. If the /tmp/toc file exists, the cat toc command lists its contents.

  • To achieve identical results without designating the TargetFile parameter, type the following:
text
ln -s /tmp/toc

See the ln command in the Commands Reference, Volume 3 for the complete syntax.

Command for removing linked files

The rm command removes the link from the file name that you indicate.

When one of several hard-linked file names is deleted, the file is not completely deleted because it remains under the other name. When the last link to an i-node number is removed, the data is removed as well. The i-node number is then available for reuse by the system.

See the rm command in the Commands Reference, Volume 3 for the complete syntax.

DOS 파일

AIX 운영 체제에서는 시스템에서 DOS 파일을 다룰 수 있습니다.

다룰 DOS 파일을 디스켓에 복사합니다. 시스템은 이 파일을 올바른 형식으로 기본 운영 체제 디렉터리에 읽어 들이고, 다시 DOS 형식으로 디스켓에 쓸 수 있습니다.

참고: 와일드카드 문자 *와 ?(별표와 물음표)는 이 절에서 다루는 명령에서 제대로 동작하지 않습니다(기본 운영 체제 셸에서는 동작합니다). 파일 이름 확장자를 지정하지 않으면 빈 확장자를 지정한 것처럼 파일 이름을 맞춥니다.

DOS 파일을 기본 운영 체제 파일로 복사

dosread 명령으로 지정한 DOS 파일을 지정한 기본 운영 체제 파일로 복사합니다.

참고: DOS 파일 이름 규칙을 쓰되 예외가 하나 있습니다. 백슬래시(\) 문자는 기본 운영 체제에서 특별한 뜻을 가질 수 있으므로, DOS 경로 이름에서 하위 디렉터리 이름을 구분할 때 슬래시(/) 문자를 씁니다.

다음 예를 봅니다.

  • chap1.doc라는 텍스트 파일을 DOS 디스켓에서 기본 운영 파일 시스템으로 복사하려면 다음을 입력합니다.
text
dosread -a chap1.doc chap1

기본 장치 /dev/fd0에 있는 DOS 텍스트 파일 \CHAP1.DOC를 현재 디렉터리의 기본 운영 체제 파일 chap1로 복사합니다.

  • 바이너리 파일을 DOS 디스켓에서 기본 운영 파일 시스템으로 복사하려면 다음을 입력합니다.
text
dosread -D/dev/fd0 /survey/test.dta /home/fran/testdata

/dev/fd0에 있는 DOS 데이터 파일 \SURVEY\TEST.DTA를 기본 운영 체제 파일 /home/fran/testdata로 복사합니다.

전체 구문은 Commands Reference, Volume 2의 dosread 명령을 봅니다.

기본 운영 체제 파일을 DOS 파일로 복사

doswrite 명령으로 지정한 기본 운영 체제 파일을 지정한 DOS 파일로 복사합니다.

참고: DOS 파일 이름 규칙을 쓰되, DOS 경로 이름에서 하위 디렉터리 이름을 구분할 때 백슬래시 대신 슬래시(/) 문자를 씁니다.

다음 예를 봅니다.

  • chap1이라는 텍스트 파일을 기본 운영 파일 시스템에서 DOS 디스켓으로 복사하려면 다음을 입력합니다.
text
doswrite -a chap1 chap1.doc

현재 디렉터리의 기본 운영 체제 파일 chap1을 /dev/fd0의 DOS 텍스트 파일 \CHAP1.DOC로 복사합니다.

  • /survey/test.dta라는 바이너리 파일을 기본 운영 파일 시스템에서 DOS 디스켓으로 복사하려면(원문 그대로) 다음을 입력합니다.
text
doswrite -D/dev/fd0 /home/fran/testdata /survey/test.dta

기본 운영 체제 데이터 파일 /home/fran/testdata를 /dev/fd0의 DOS 파일 \SURVEY\TEST.DTA로 복사합니다.

전체 구문은 Commands Reference, Volume 2의 doswrite 명령을 봅니다.

DOS 파일 지우기

dosdel 명령으로 지정한 DOS 파일을 지웁니다.

참고: DOS 파일 이름 규칙을 쓰되, DOS 경로 이름에서 하위 디렉터리 이름을 구분할 때 백슬래시 대신 슬래시(/) 문자를 씁니다.

dosdel 명령은 디스크를 확인하기 전에 파일이나 디렉터리 이름의 소문자를 대문자로 바꿉니다. 모든 파일 이름을 (상대가 아닌) 전체 경로 이름으로 보므로 처음의 슬래시(/)를 붙이지 않아도 됩니다.

예를 들어 기본 장치(/dev/fd0)에서 file.ext라는 DOS 파일을 지우려면 다음을 입력합니다.

text
dosdel file.ext

전체 구문은 Commands Reference, Volume 2의 dosdel 명령을 봅니다.

DOS 디렉터리 내용 보기

dosdir 명령으로 지정한 DOS 파일이나 디렉터리에 관한 정보를 봅니다.

참고: DOS 파일 이름 규칙을 쓰되, DOS 경로 이름에서 하위 디렉터리 이름을 구분할 때 백슬래시 대신 슬래시(/) 문자를 씁니다.

dosdir 명령은 디스크를 확인하기 전에 파일이나 디렉터리 이름의 소문자를 대문자로 바꿉니다. 모든 파일 이름을 (상대가 아닌) 전체 경로 이름으로 보므로 처음의 슬래시(/)를 붙이지 않아도 됩니다.

예를 들어 /dev/fd0의 DOS 파일 디렉터리를 읽으려면 다음을 입력합니다.

text
dosdir

이 명령은 파일 이름과 디스크 공간 정보를 다음과 비슷하게 돌려줍니다.

text
PG3-25.TXT
PG4-25.TXT
PG5-25.TXT
PG6-25.TXT
Free space: 312320 bytes

전체 구문은 Commands Reference, Volume 2의 dosdir 명령을 봅니다.

영어 원문

DOS files

The AIX operating system allows you to work with DOS files on your system.

Copy to a diskette the DOS files you want to work with. Your system can read these files into a base operating system directory in the correct format and back onto the diskette in DOS format.

Note: The wildcard characters * and ? (asterisk and question mark) do not work correctly with the commands discussed in this section (although they do with the base operating system shell). If you do not specify a file name extension, the file name is matched as if you had specified a blank extension.

Copying DOS files to base operating system files

Use the dosread command to copy the specified DOS file to the specified base operating system file.

Note: DOS file-naming conventions are used with one exception. Because the backslash (\) character can have special meaning to the base operating system, use a slash (/) character as the delimiter to specify subdirectory names in a DOS path name.

See the following examples:

  • To copy a text file named chap1.doc from a DOS diskette to the base operating file system, type the following:
text
dosread -a chap1.doc chap1

This copies the DOS text file \CHAP1.DOC on the /dev/fd0 default device to the base operating system file chap1 in the current directory.

  • To copy a binary file from a DOS diskette to the base operating file system, type the following:
text
dosread -D/dev/fd0 /survey/test.dta /home/fran/testdata

This copies the \SURVEY\TEST.DTA DOS data file on /dev/fd0 to the base operating system file /home/fran/testdata.

See the dosread command in the Commands Reference, Volume 2 for the complete syntax.

Copying base operating system files to DOS files

Use the doswrite command to copy the specified base operating system file to the specified DOS file.

Note: DOS file-naming conventions are used with one exception. Because the backslash (\) character can have special meaning to the base operating system, use a slash (/) character as the delimiter to specify subdirectory names in a DOS path name.

See the following examples:

  • To copy a text file named chap1 from the base operating file system to a DOS diskette, type the following:
text
doswrite -a chap1 chap1.doc

This copies the base operating system file chap1 in the current directory to the DOS text file \CHAP1.DOC on /dev/fd0.

  • To copy a binary file named /survey/test.dta from the base operating file system to a DOS diskette, type the following:
text
doswrite -D/dev/fd0 /home/fran/testdata /survey/test.dta

This copies the base operating system data file /home/fran/testdata to the DOS file \SURVEY\TEST.DTA on /dev/fd0.

See the doswrite command in the Commands Reference, Volume 2 for the complete syntax.

Deleting DOS files

Use the dosdel command to delete the specified DOS file.

Note: DOS file-naming conventions are used with one exception. Because the backslash (\) character can have special meaning to the base operating system, use a slash (/) character as the delimiter to specify subdirectory names in a DOS path name.

The dosdel command converts lowercase characters in the file or directory name to uppercase before it checks the disk. Because all file names are assumed to be full (not relative) path names, you need not add the initial slash (/).

For example, to delete a DOS file named file.ext on the default device (/dev/fd0), type the following:

text
dosdel file.ext

See the dosdel command in the Commands Reference, Volume 2 for the complete syntax.

Displaying contents of a DOS directory

Use the dosdir command to display information about the specified DOS files or directories.

Note: DOS file-naming conventions are used with one exception. Because the backslash (\) character can have special meaning to the base operating system, use a slash (/) character as the delimiter to specify subdirectory names in a DOS path name.

The dosdir command converts lowercase characters in the file or directory name to uppercase before it checks the disk. Because all file names are assumed to be full (not relative) path names, you need not add the initial / (slash).

For example, to read a directory of the DOS files on /dev/fd0, type the following:

text
dosdir

The command returns the names of the files and disk-space information, similar to the following.

text
PG3-25.TXT
PG4-25.TXT
PG5-25.TXT
PG6-25.TXT
Free space: 312320 bytes

See the dosdir command in the Commands Reference, Volume 2 for the complete syntax.

파일 명령 요약

다음은 파일, 파일 처리 절차, DOS 파일에 쓰는 명령입니다. 파일과 디렉터리를 링크하는 명령 목록도 있습니다.

표 57. 파일에 관한 명령

기호 설명
* 와일드카드. 아무 문자와 일치
? 와일드카드. 아무 한 문자와 일치
[ ] 메타 문자. 감싼 문자와 일치

표 58. 파일 처리 절차에 관한 명령

명령 설명
cat 파일을 이어 붙이거나 보여 줌
cmp 두 파일을 비교함
colrm 파일에서 열을 뽑아냄(실제로는 지움)
cp 파일을 복사함
cut 파일 각 줄에서 고른 바이트, 문자, 필드를 씀
diff 텍스트 파일을 비교함
file 파일 종류를 판단함
find 식과 맞는 파일을 찾음
grep 파일에서 패턴을 찾음
head 파일의 처음 몇 줄이나 바이트를 보여 줌
more 이어지는 텍스트를 화면에 한 화면씩 보여 줌
mv 파일을 옮김
nl 파일의 줄에 번호를 매김
pg 파일을 화면에 맞춰 보여 줌
rm 파일이나 디렉터리를 지움(링크 해제)
paste 여러 파일의 줄이나 한 파일의 이어지는 줄을 합침
sort 파일을 정렬하고, 이미 정렬된 파일을 합치고, 정렬됐는지 확인함
tail 파일을 지정한 지점부터 표준 출력에 씀
wc 파일의 줄, 단어, 바이트 수를 셈

표 59. 파일과 디렉터리 링크 명령

명령 설명
ln 파일과 디렉터리를 링크함

표 60. DOS 파일에 관한 명령

명령 설명
dosdel DOS 파일을 지움
dosdir DOS 파일의 디렉터리를 나열함
dosread DOS 파일을 기본 운영 체제 파일로 복사함
doswrite 기본 운영 체제 파일을 DOS 파일로 복사함
영어 원문

Command summary for files

The following are commands for files, file handling procedures, and DOS files. There is also a list of commands for linking files and directories.

Table 57. Commands for files

  • * — Wildcard, matches any characters
  • ? — Wildcard, matches any single character
  • — Metacharacters, matches enclosed characters.

Table 58. Commands for file handling procedures

  • cat — Concatenates or displays files
  • cmp — Compares two files
  • colrm — Extracts columns from a file
  • cp — Copies files
  • cut — Writes out selected bytes, characters, or fields from each line of a file
  • diff — Compares text files
  • file — Determines the file type
  • find — Finds files with a matching expression
  • grep — Searches a file for a pattern
  • head — Displays the first few lines or bytes of a file or files
  • more — Displays continuous text one screen at a time on a display screen
  • mv — Moves files
  • nl — Numbers lines in a file
  • pg — Formats files to the display
  • rm — Removes (unlinks) files or directories
  • paste — Merges the lines of several files or subsequent lines in one file
  • sort — Sorts files, merges files that are already sorted, and checks files to determine if they have been sorted
  • tail — Writes a file to standard output, beginning at a specified point
  • wc — Counts the number of lines, words, and bytes in a file

Table 59. Command for linking files and directories

  • ln — Links files and directories

Table 60. Commands for DOS files

  • dosdel — Deletes DOS files
  • dosdir — Lists the directory for DOS files
  • dosread — Copies DOS files to Base Operating System files
  • doswrite — Copies Base Operating System files to DOS files

운영 체제 셸

운영 체제와의 인터페이스를 셸이라고 합니다.

셸은 운영 체제의 가장 바깥 층입니다. 셸에는 프로세스와 파일을 제어하고 다른 프로그램을 시작·제어하는 프로그래밍 언어가 들어 있습니다. 셸은 입력을 요청하고, 그 입력을 운영 체제를 위해 해석하고, 운영 체제가 내놓은 출력을 처리해 사용자와 운영 체제 사이의 상호 작용을 관리합니다.

셸은 운영 체제와 소통하는 방법을 제공합니다. 이 소통은 대화식(키보드 입력이 바로 처리됨)이나 셸 스크립트로 이루어집니다. 셸 스크립트는 셸과 운영 체제 명령을 차례로 파일에 저장한 것입니다.

시스템에 로그인하면 시스템은 실행할 셸 프로그램 이름을 찾습니다. 셸이 실행되면 명령 프롬프트를 보여 줍니다. 이 프롬프트는 보통 $(달러 기호)입니다. 프롬프트에서 명령을 입력하고 Enter 키를 누르면 셸은 명령을 평가해 실행하려고 합니다. 명령에 따라 셸은 명령 출력을 화면에 쓰거나 방향을 바꿉니다. 그런 다음 명령 프롬프트를 다시 보여 주고 다음 명령을 기다립니다.

명령행은 입력하는 줄입니다. 셸 프롬프트도 들어 있습니다. 각 줄의 기본 형식은 다음과 같습니다.

text
$ Command Argument(s)

셸은 명령행의 첫 단어(첫 공백까지)를 명령으로, 그 뒤의 모든 단어를 인수로 봅니다.

참고: libc.a를 옮기거나 이름을 바꾸면 시스템이 유틸리티를 적재해 실행할 libc.a 파일이 없으므로 셸에서 Killed 오류 메시지가 나옵니다. recsh 명령은 복구 셸을 띄워, 실수로 옮긴 libc.a의 이름을 되돌릴 수 있게 합니다.

관련 작업

  • 이전에 입력한 명령 나열(history 명령)
영어 원문

Operating system shells

Your interface to the operating system is called a shell.

The shell is the outermost layer of the operating system. Shells incorporate a programming language to control processes and files, as well as to start and control other programs. The shell manages the interaction between you and the operating system by prompting you for input, interpreting that input for the operating system, and then handling any resulting output from the operating system.

Shells provide a way for you to communicate with the operating system. This communication is carried out either interactively (input from the keyboard is acted upon immediately) or as a shell script. A shell script is a sequence of shell and operating system commands that is stored in a file.

When you log in to the system, the system locates the name of a shell program to execute. After it is executed, the shell displays a command prompt. This prompt is usually a $ (dollar sign). When you type a command at the prompt and press the Enter key, the shell evaluates the command and attempts to carry it out. Depending on your command instructions, the shell writes the command output to the screen or redirects the output. It then returns the command prompt and waits for you to type another command.

A command line is the line on which you type. It contains the shell prompt. The basic format for each line is as follows:

text
$ Command Argument(s)

The shell considers the first word of a command line (up to the first blank space) as the command and all subsequent words as arguments.

Note: When libc.a is moved or renamed, the Killed error message is displayed from the shell because there is no libc.a file available for the system to load and run the utilities. The recsh command invokes the recovery shell, which provides an ability to rename libc.a if it is accidently moved.

Related tasks

Listing previously entered commands (history command) Use the history command to list commands that you have previously entered.

셸 개념

AIX에서 쓸 수 있는 여러 셸을 다루기 전에 기본 용어와 기능을 알아야 합니다.

제공되는 셸

AIX에서 제공하는 셸은 다음과 같습니다.

  • Korn 셸(ksh 명령으로 시작)
  • Bourne 셸(bsh 명령으로 시작)
  • 제한 셸(Bourne 셸의 제한판, Rsh 명령으로 시작)
  • POSIX 셸(Korn 셸이라고도 하며 psh 명령으로 시작)
  • Korn 셸(ksh와 ksh93)의 제한 셸. ksh와 ksh93 셸에는 각각 제한 셸 rksh와 rksh93이 함께 제공됩니다.
  • 기본 셸(sh 명령으로 시작)
  • C 셸(csh 명령으로 시작)
  • 신뢰 셸(Korn 셸의 제한판, tsh 명령으로 시작)
  • 원격 셸(rsh 명령으로 시작)

로그인 셸은 컴퓨터 시스템에 로그인할 때 적재되는 셸입니다. 로그인 셸은 /etc/passwd 파일에 설정합니다. Korn 셸은 운영 체제의 표준 로그인 셸이며 Bourne 셸과 하위 호환됩니다.

Korn 셸(/usr/bin/ksh)이 기본 셸로 설정돼 있습니다. 기본 셸 또는 표준 셸은 /usr/bin/sh 명령에 링크돼 그 명령으로 시작하는 셸을 말합니다. Bourne 셸(/usr/bin/sh, 원문 그대로)을 기본 셸로 바꿔 쓸 수 있습니다. /usr/bin/psh 명령으로 호출하는 POSIX 셸은 /usr/bin/sh 명령에 대한 링크로 있습니다.

관련 개념

  • Bourne 셸 — 대화식 명령 해석기이자 명령 프로그래밍 언어입니다.
  • Korn 셸 또는 POSIX 셸 명령 — Korn 셸은 대화식 명령 해석기이자 명령 프로그래밍 언어이며, 운영 체제의 국제 표준인 POSIX(Portable Operating System Interface for Computer Environments)를 따릅니다.

셸 용어

다음 용어와 정의는 셸을 이해하는 데 도움이 됩니다.

blank(공백) — LC_CTYPE 범주에 정의된 blank 문자 클래스의 문자 가운데 하나입니다. POSIX 셸에서 blank는 탭이나 스페이스입니다.

built-in command(내장 명령) — 셸이 찾아서 별도 프로세스를 만들지 않고 실행하는 명령입니다.

command(명령) — 셸 언어 구문으로 된 문자열입니다. 셸은 각 명령을 읽고 원하는 동작을 직접 하거나 별도 유틸리티를 호출해 합니다.

comment(주석) — 샵 기호(#)로 시작하는 단어입니다. 그 단어와 다음 줄 바꿈 문자까지의 모든 문자는 무시됩니다.

identifier(식별자) — 이식 가능한 문자 집합의 문자, 숫자, 밑줄로 된 문자열로, 문자나 밑줄로 시작합니다. 식별자의 첫 문자는 숫자일 수 없습니다. 식별자는 별명, 함수, 이름 있는 매개변수의 이름으로 씁니다.

list(목록) — 다음 기호 가운데 하나로 구분한 파이프라인 하나 이상의 연속입니다. 세미콜론(;), 앰퍼샌드(&), 이중 앰퍼샌드(&&), 이중 막대(||). 목록은 선택적으로 세미콜론(;), 앰퍼샌드(&), 막대 앰퍼샌드(|&) 가운데 하나로 끝납니다.

  • ; — 앞 파이프라인을 순차 처리합니다. 셸은 각 명령을 차례로 실행하고 가장 최근 명령이 끝나기를 기다립니다.
  • & — 앞 파이프라인을 비동기 처리합니다. 셸은 각 명령을 차례로 실행하되, 파이프라인을 백그라운드에서 처리하며 끝나기를 기다리지 않습니다.
  • |& — 앞 파이프라인을 비동기 처리하고 부모 셸과 양방향 파이프를 맺습니다. 셸은 파이프라인을 백그라운드에서 처리하며 끝나기를 기다리지 않습니다. 부모 셸은 read -p와 print -p 명령으로 만든 명령의 표준 입력과 출력을 읽고 쓸 수 있습니다. 이런 명령은 한 번에 하나만 활성일 수 있습니다.
  • && — 앞 파이프라인이 종료 값 0을 돌려줄 때만 이 기호 뒤의 목록을 처리합니다.
  • || — 앞 파이프라인이 0이 아닌 종료 값을 돌려줄 때만 이 기호 뒤의 목록을 처리합니다.

세미콜론(;), 앰퍼샌드(&), 막대 앰퍼샌드(|&)는 이중 앰퍼샌드(&&)와 이중 막대(||)보다 우선순위가 낮습니다. ;, &, |& 기호끼리는 우선순위가 같습니다. &&와 || 기호도 우선순위가 같습니다. 목록에서 두 명령을 구분할 때 세미콜론 대신 줄 바꿈 문자를 하나 이상 쓸 수 있습니다.

참고: |& 기호는 Korn 셸에서만 유효합니다.

metacharacter(메타 문자) — 메타 문자마다 셸에 특별한 뜻이 있으며, 따옴표로 감싸지 않으면 단어를 끝냅니다. 메타 문자는 파이프(|), 앰퍼샌드(&), 세미콜론(;), 작다 기호(<), 크다 기호(>), 여는 괄호((), 닫는 괄호()), 달러 기호($), 역따옴표(원문은 작은따옴표로 찍힘), 백슬래시(\), 오른쪽 따옴표, 큰따옴표("), 줄 바꿈 문자, 스페이스 문자, 탭 문자입니다. 작은따옴표 사이의 모든 문자는 따옴표로 감싼 것으로 보아 셸이 글자 그대로 해석합니다. 따옴표로 감싸지 않으면 메타 문자의 특별한 뜻이 유지됩니다(C 셸에서는 메타 문자를 파서 메타 문자라고도 합니다).

parameter assignment list(매개변수 할당 목록) — Identifier=Value 꼴의 단어 하나 이상으로, 등호(=) 양쪽의 공백이 균형을 이뤄야 합니다. 곧 앞뒤에 공백을 모두 두거나 모두 두지 않아야 합니다.

참고: C 셸에서 매개변수 할당 목록은 set Identifier = Value 꼴이며 등호(=) 양쪽의 공백이 필요합니다.

pipeline(파이프라인) — 파이프(|)로 구분한 명령 하나 이상의 연속입니다. 마지막 명령을 뺀 파이프라인의 각 명령은 별도 프로세스로 실행됩니다. 파이프로 이은 각 명령의 표준 출력은 다음 명령의 표준 입력이 됩니다. 목록을 괄호로 감싸면 별도 서브셸에서 동작하는 단순 명령으로 실행됩니다. 파이프라인 앞에 예약어 !가 없으면 종료 상태는 파이프라인의 마지막 명령의 종료 상태입니다. 있으면 종료 상태는 마지막 명령 종료 상태의 논리 NOT입니다. 곧 마지막 명령이 0을 돌려주면 종료 상태는 1이고, 0보다 크면 종료 상태는 0입니다. 파이프라인 형식은 [!] command1 [ | command2 ...]입니다.

참고: 초기 Bourne 셸은 파이프를 나타내는 데 캐럿(^)을 썼습니다.

shell variable(셸 변수) — 값을 할당한 이름이나 매개변수입니다. 변수 이름, 등호(=), 값을 차례로 입력해 할당합니다. 변수 이름 앞에 달러 기호($)를 붙이면 할당한 값으로 치환됩니다. 변수는 홈 디렉터리를 뜻하는 $HOME처럼 긴 경로 이름을 짧게 쓰는 데 특히 쓸모 있습니다. 미리 정의된 변수는 셸이 값을 할당하는 변수이고, 사용자 정의 변수는 사용자가 값을 할당하는 변수입니다.

simple command(단순 명령) — 선택적인 매개변수 할당 목록과 방향 바꾸기를 아무 순서로 늘어놓은 것입니다. 그 뒤에 명령, 단어, 방향 바꾸기가 선택적으로 올 수 있습니다. ;, |, &, ||, &&, |&, 줄 바꿈 문자로 끝납니다. 명령 이름은 (exec 서브루틴이 정의한 대로) 매개변수 0으로 넘어갑니다. 단순 명령의 값은 종료 상태로, 정상 종료면 0, 비정상 종료면 0이 아닌 값입니다. sigaction, sigvec, signal 서브루틴에 신호별 종료 상태 값 목록이 있습니다.

subshell(서브셸) — 로그인 셸이나 현재 셸의 자식으로 실행 중인 셸입니다.

wildcard character(와일드카드 문자) — 패턴 일치 문자라고도 합니다. 셸이 할당된 값과 연결합니다. 기본 와일드카드는 ?, *, [set], [!set]입니다. 와일드카드 문자는 파일 이름 치환을 할 때 특히 쓸모 있습니다.

word(단어) — 공백이 없는 문자열입니다. 단어는 메타 문자 하나 이상으로 구분됩니다.

스크립트 파일의 셸 지정

Korn 셸(POSIX 셸)이나 Bourne 셸에서 실행 가능한 셸 스크립트를 실행하면, 다른 셸을 지정하지 않는 한 스크립트의 명령은 현재 셸(스크립트를 시작한 셸)의 제어 아래 실행됩니다. C 셸에서 실행 가능한 셸 스크립트를 실행하면, 다른 셸을 지정하지 않는 한 스크립트의 명령은 Bourne 셸(/usr/bin/bsh)의 제어 아래 실행됩니다.

셸 스크립트 안에 셸을 적어 특정 셸에서 스크립트를 실행할 수 있습니다.

실행 가능한 셸 스크립트를 특정 셸에서 실행하려면 셸 스크립트 첫 줄에 #!Path를 입력하고 Enter를 누릅니다. #! 문자가 파일 종류를 나타냅니다. Path 변수는 셸 스크립트를 실행할 셸의 경로 이름입니다.

예를 들어 bsh 스크립트를 Bourne 셸에서 실행하려면 다음을 입력합니다.

text
#!/usr/bin/bsh

셸 스크립트 파일 이름 앞에 셸 명령을 쓰면 명령행에 지정한 셸이 스크립트 파일 안에 지정한 셸보다 우선합니다. 그래서 ksh myfile을 입력하고 Enter를 누르면 myfile의 첫 줄이 #!/usr/bin/csh라도 myfile이라는 파일이 Korn 셸의 제어 아래 실행됩니다.

셸 기능

셸을 시스템 인터페이스로 쓰면 여러 이점이 있습니다.

셸로 시스템과 접하는 주된 이점은 다음과 같습니다.

  • 파일 이름의 와일드카드 치환(패턴 일치) — 실제 파일 이름 대신 맞출 패턴을 지정해 파일 묶음에 명령을 실행합니다. 자세한 내용은 Korn·POSIX 셸, Bourne 셸, C 셸의 파일 이름 치환을 봅니다.
  • 백그라운드 처리 — 오래 걸리는 작업을 백그라운드에서 실행하게 해 터미널을 동시에 대화식으로 쓸 수 있게 합니다. 자세한 내용은 Korn·POSIX 셸의 작업 제어와 C 셸 내장 명령의 bg 명령을 봅니다. 참고: Bourne 셸은 작업 제어를 지원하지 않습니다.
  • 명령 별명 — 명령이나 구문에 별명을 붙입니다. 셸은 명령행이나 셸 스크립트에서 별명을 만나면 별명이 가리키는 텍스트로 바꿉니다. 자세한 내용은 Korn·POSIX 셸의 명령 별명과 C 셸의 별명 치환을 봅니다. 참고: Bourne 셸은 명령 별명을 지원하지 않습니다.
  • 명령 기록 — 입력한 명령을 기록 파일에 남깁니다. 이 파일로 나열된 명령을 쉽게 찾고 고치고 다시 실행할 수 있습니다. 자세한 내용은 Korn·POSIX 셸 명령 기록, C 셸 내장 명령, C 셸의 기록 치환에 있는 history 명령을 봅니다. 참고: Bourne 셸은 명령 기록을 지원하지 않습니다.
  • 파일 이름 치환 — 패턴 일치 문자로 명령행에 파일 이름 목록을 자동으로 만듭니다. 자세한 내용은 각 셸의 파일 이름 치환을 봅니다.
  • 입출력 방향 바꾸기 — 입력을 키보드가 아닌 곳에서 받고 출력을 터미널이 아닌 파일이나 장치로 보냅니다. 예를 들어 프로그램 입력을 파일에서 주고 출력을 프린터나 다른 파일로 보낼 수 있습니다. 자세한 내용은 각 셸의 입출력 방향 바꾸기를 봅니다.
  • 파이프 — 명령을 여러 개 이어 복잡한 프로그램을 만듭니다. 한 프로그램의 표준 출력이 다음 프로그램의 표준 입력이 됩니다. 자세한 내용은 셸 용어의 pipeline 정의를 봅니다.
  • 셸 변수 치환 — 데이터를 사용자 정의 변수와 미리 정의된 셸 변수에 저장합니다. 자세한 내용은 Korn·POSIX 셸의 매개변수 치환, Bourne 셸과 C 셸의 변수 치환을 봅니다.

관련 개념

  • 명령

문자 클래스

문자 클래스로 파일 이름을 맞출 수 있습니다.

다음과 같이 문자 클래스로 파일 이름을 맞춥니다.

text
[[: charclass :]]

이 형식은 지정한 클래스에 속한 아무 한 문자와 일치시키라고 시스템에 지시합니다. 정의된 클래스는 다음과 같이 ctype 서브루틴과 대응합니다.

클래스 일치하는 문자
alnum 영숫자
alpha 대문자와 소문자
blank 스페이스나 가로 탭
cntrl 제어 문자
digit 숫자
graph 그래픽 문자
lower 소문자
print 출력 가능한 문자
punct 구두점 문자
space 스페이스, 가로 탭, 캐리지 리턴, 줄 바꿈, 세로 탭, 폼 피드 문자
upper 대문자
xdigit 16진 숫자

제한 셸

제한 셸은 일반 Bourne 셸보다 기능을 더 통제하는 로그인 이름과 실행 환경을 설정하는 데 씁니다.

Rsh나 bsh -r 명령이 제한 셸을 엽니다. 이 명령들은 다음 동작이 허용되지 않는다는 점만 빼면 bsh 명령과 똑같이 동작합니다.

  • (cd 명령으로) 디렉터리 바꾸기
  • PATH나 SHELL 변수 값 설정
  • 슬래시(/)가 든 경로나 명령 이름 지정
  • 출력 방향 바꾸기

제한 셸은 실행할 명령이 셸 프로시저라고 판단하면 Bourne 셸로 그 명령을 실행합니다. 이렇게 하면 사용자에게 제한된 명령 메뉴만 주면서 Bourne 셸의 모든 기능에 접근하는 셸 프로시저를 제공할 수 있습니다. 이때 사용자는 같은 디렉터리에 쓰기와 실행 권한을 함께 가지지 않는다고 가정합니다.

Bourne 셸을 시작할 때 File [Parameter] 매개변수를 지정하면 셸은 File 매개변수로 지정한 스크립트 파일을 지정한 매개변수와 함께 실행합니다. 지정한 스크립트 파일에는 읽기 권한이 있어야 합니다. 스크립트 파일의 setuid와 setgid 설정은 무시됩니다. 그런 다음 셸은 명령을 읽습니다. -c나 -s 플래그를 쓰면 스크립트 파일을 지정하지 않습니다.

Rsh 명령으로 시작하면 셸은 .profile과 /etc/environment 파일을 해석한 뒤 제한을 겁니다. 그래서 .profile 파일 작성자는 설정 작업을 하고 사용자를 알맞은 디렉터리(아마 로그인 디렉터리가 아닌 곳)에 두어 사용자 동작을 완전히 통제할 수 있습니다. 관리자는 /usr/rbin 디렉터리에 명령 디렉터리를 만들고 PATH 변수에 그 디렉터리를 넣어 Rsh 명령이 쓰게 할 수 있습니다. bsh -r 명령으로 시작하면 셸은 .profile 파일을 해석할 때 제한을 적용합니다.

Rsh라는 이름으로 호출하면 제한 셸은 사용자의 .profile 파일($HOME/.profile)을 읽습니다. 이 동안에는 인터럽트가 명령 수준으로 돌아가는 대신 바로 종료한다는 점만 빼면 일반 Bourne 셸처럼 동작합니다.

Korn 셸은 ksh -r 명령으로 제한 셸로 시작할 수 있습니다.

ksh와 rksh의 inode는 같고, ksh93과 rksh93의 inode도 같습니다.

셸 스크립트 만들기와 실행

셸 스크립트는 명령이 하나 이상 든 파일입니다. 셸 스크립트를 쓰면 지루한 명령, 크거나 복잡한 명령 순서, 일상 작업을 쉽게 할 수 있습니다. 셸 스크립트 파일 이름을 입력하면 시스템이 파일에 든 명령 순서를 실행합니다.

텍스트 편집기로 셸 스크립트를 만들 수 있습니다. 스크립트에는 운영 체제 명령과 셸 내장 명령을 모두 넣을 수 있습니다.

셸 스크립트를 쓰는 일반 지침은 다음과 같습니다.

  1. 텍스트 편집기로 파일을 만들고 저장합니다. 셸 스크립트 파일에는 셸과 운영 체제 명령을 어떻게 조합해도 됩니다. 관례상 여러 사용자가 쓰도록 만들지 않은 셸 스크립트는 $HOME/bin 디렉터리에 둡니다.

    참고: 운영 체제는 셸 스크립트 안의 setuid나 setgid 서브루틴을 지원하지 않습니다.

  2. chmod 명령으로 소유자만 파일을 실행할 수 있게 합니다. 예를 들어 파일 이름이 script1이면 다음을 입력합니다.

text
chmod u=rwx script1
  1. 명령행에 스크립트 이름을 입력해 셸 스크립트를 실행합니다. script1 셸 스크립트를 실행하려면 다음을 입력합니다.
text
script1

참고: 명령행에서 셸 스크립트 파일 이름 앞에 셸 명령(ksh, bsh, csh)을 쓰면 실행 가능하게 만들지 않아도 셸 스크립트를 실행할 수 있습니다. 예를 들어 실행할 수 없는 script1이라는 파일을 Korn 셸의 제어 아래 실행하려면 다음을 입력합니다.

text
ksh script1

관련 개념

  • 명령
영어 원문

Shell concepts

Before you start working with the different types of shells available for AIX you need to understand basic terminology and features.

Available shells

The following are the shells that are provided with AIX.

  • Korn shell (started with the ksh command)

  • Bourne shell (started with the bsh command)

  • Restricted shell (a limited version of the Bourne shell, and started with the Rsh command)

  • POSIX shell (also known as the Korn Shell, and started with the psh command)

  • Restricted shell for the Korn shell (ksh and ksh93). The ksh and ksh93 shells are provided with their restricted shell equivalents rksh and rksh93.

  • Default shell (started with the sh command)

  • C shell (started with the csh command)

  • Trusted shell (a limited version of the Korn shell, and started with the tsh command)

  • Remote shell (started with the rsh command)

The login shell refers to the shell that is loaded when you log in to the computer system. Your login shell is set in the /etc/passwd file. The Korn shell is the standard operating system login shell and is backward-compatible with the Bourne Shell.

The Korn shell (/usr/bin/ksh) is set up as the default shell. The default or standard shell refers to the shells linked to and started with the /usr/bin/sh command. The Bourne shell (/usr/bin/sh) can be substituted as the default shell. The POSIX shell, which is invoked by the /usr/bin/psh command, resides as a link to the /usr/bin/sh command.

Related concepts

Bourne shell The Bourne shell is an interactive command interpreter and command programming language. 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.

Shells terminology

The terms and definitions in this table are helpful in understanding shells.

  • blank — A blank is one of the characters in the blank character class defined in the LC_CTYPE category. In the POSIX shell, a blank is either a tab or space.
  • built-in command — A command that the shell executes without searching for it and creating a separate process.
  • command — A sequence of characters in the syntax of the shell language. The shell reads each command and carries out the desired action either directly or by invoking separate utilities.
  • comment — Any word that begins with pound sign (#). The word and all characters that follow it, until the next newline character, are ignored.
  • identifier — A sequence of letters, digits, or underscores from the portable character set, starting with a letter or underscore. The first character of an identifier must not be a digit. Identifiers are used as names for aliases, functions, and named parameters.
  • list — A sequence of one or more pipelines separated by one of the following symbols: semicolon (;), ampersand (&), double ampersand (&&), or double bar (||). The list is optionally ended by one of the following symbols: semicolon (;), ampersand (&), or bar ampersand (|&). ; Sequentially processes the preceding pipeline. The shell carries out each command in turn and waits for the most recent command to complete. & Asynchronously processes the preceding pipeline. The shell carries out each command in turn, processing the pipeline in the background without waiting for it to complete. |& Asynchronously processes the preceding pipeline and establishes a two-way pipe to the parent shell. The shell carries out each command in turn, processing the pipeline in the background without waiting for it to complete. The parent shell can read from and write to the standard input and output of the created command by using the read -p and print -p commands. Only one such command can be active at any given time. && Processes the list that follows this symbol only if the preceding pipeline returns an exit value of zero (0). || Processes the list that follows this symbol only if the preceding pipeline returns a nonzero exit value. The semicolon (;), ampersand (&), and bar ampersand (|&) have a lower priority than the double ampersand (&&) and double bar (||). The ;, &, and |& symbols have equal priority among themselves. The && and || symbols are equal in priority. One or more newline characters can be used instead of a semicolon to delimit two commands in a list. Note: The |& symbol is valid only in the Korn shell.
  • metacharacter — Each metacharacter has a special meaning to the shell and causes termination of a word unless it is quoted. Metacharacters are: pipe (|), ampersand (&), semicolon (;), less-than sign (<), greater-than sign (>), left parenthesis ((), right parenthesis ()), dollar sign ($), backquote ('), backslash (\), right quote (’), double quotation marks ("), newline character, space character, and tab character. All characters enclosed between single quotation marks are considered quoted and are interpreted literally by the shell. The special meaning of metacharacters is retained if not quoted. (Metacharacters are also known as parser metacharacters in the C shell.)
  • parameter assignment list — Includes one or more words of the form Identifier=Value in which spaces surrounding the equal sign (=) must be balanced. That is, leading and trailing blanks, or no blanks, must be used. Note: In the C shell, the parameter assignment list is of the form setIdentifier=Value. The spaces surrounding the equal sign (=) are required.
  • pipeline — A sequence of one or more commands separated by pipe (|). Each command in the pipeline, except possibly the last command, is run as a separate process. However, the standard output of each command that is connected by a pipe becomes the standard input of the next command in the sequence. If a list is enclosed with parentheses, it is carried out as a simple command that operates in a separate subshell. If the reserved word ! does not precede the pipeline, the exit status will be the exit status of the last command specified in the pipeline. Otherwise, the exit status is the logical NOT of the exit status of the last command. In other words, if the last command returns zero, the exit status will be 1. If the last command returns greater than zero, the exit status will be zero. The format for a pipeline is as follows: [!] command1 [ | command2 ...] Note: Early versions of the Bourne shell used the caret (^) to indicate a pipe.
  • shell variable — A name or parameter to which a value is assigned. Assign a variable by typing the variable name, an equal sign (=), and then the value. The variable name can be substituted for the assigned value by preceding the variable name with a dollar sign ($). Variables are particularly useful for creating a short notation for a long path name, such as $HOME for the home directory. A predefined variable is one whose value is assigned by the shell. A user-defined variable is one whose value is assigned by a user.
  • simple command — A sequence of optional parameter assignment lists and redirections, in any sequence. They are optionally followed by commands, words, and redirections. They are terminated by ;, |, &, ||, &&, |&, or a newline character. The command name is passed as parameter 0 (as defined by the exec subroutine). The value of a simple command is its exit status of zero if it terminates normally or nonzero if it terminates abnormally. The sigaction, sigvec, or signal subroutine includes a list of signal-exit status values.
  • subshell — A shell that is running as a child of the login shell or the current shell.
  • wildcard character — Also known as a pattern-matching character. The shell associates them with assigned values. The basic wildcards are ?, *, [set], and [!set]. Wildcard characters are particularly useful when performing file name substitution.
  • word — A sequence of characters that does not contain any blanks. Words are separated by one or more metacharacters.

Specifying a shell for a script file

When you run an executable shell script in either the Korn (the POSIX Shell) or Bourne shell, the commands in the script are carried out under the control of the current shell (the shell from which the script is started) unless you specify a different shell. When you run an executable shell script in the C shell, the commands in the script are carried out under the control of the Bourne shell (/usr/bin/bsh) unless you specify a different shell.

You can run a shell script in a specific shell by including the shell within the shell script.

To run an executable shell script under a specific shell, type #!Path on the first line of the shell script, and press Enter. The #! characters identify the file type. The Path variable specifies the path name of the shell from which to run the shell script.

For example, to run the bsh script in the Bourne shell, type the following:

text
#!/usr/bin/bsh

When you precede a shell script file name with a shell command, the shell specified on the command line overrides any shell specified within the script file itself. Therefore, typing ksh myfile and pressing Enter runs the file named myfile under the control of the Korn shell, even if the first line of myfile is #!/usr/bin/csh.

Shell features

There are advantages to using the shell as an interface to the system.

The primary advantages of interfacing to the system through a shell are as follows:

  • Wildcard substitution in file names (pattern-matching) Carries out commands on a group of files by specifying a pattern to match, rather than specifying an actual file name. For more information, see: – File name substitution in the Korn shell or POSIX shell – File name substitution in the Bourne shell – File name substitution in the C shell

  • Background processing Sets up lengthy tasks to run in the background, freeing the terminal for concurrent interactive processing. For more information, see the bg command in the following:

– Job control in the Korn shell or POSIX shell – C shell built-in commands

Note: The Bourne shell does not support job control.

  • Command aliasing Gives an alias name to a command or phrase. When the shell encounters an alias on the command line or in a shell script, it substitutes the text to which the alias refers. For more information, see: – Command aliasing in the Korn shell or POSIX shell – Alias substitution in the C shell

Note: The Bourne shell does not support command aliasing.

  • Command history Records the commands you enter in a history file. You can use this file to easily access, modify, and reissue any listed command. For more information, see the history command in the following: – Korn shell or POSIX shell command history – C shell built-in commands – History substitution in the C shell

Note: The Bourne shell does not support command history.

  • File name substitution Automatically produces a list of file names on a command line using pattern-matching characters. For more information, see: – File name substitution in the Korn shell or POSIX shell – File name substitution in the Bourne shell – File name substitution in the C shell

  • Input and output redirection Redirects input away from the keyboard and redirects output to a file or device other than the terminal. For example, input to a program can be provided from a file and redirected to the printer or to another file. For more information, see: – Input and output redirection in the Korn shell or POSIX shell – Input and output redirection in the Bourne shell – Input and output redirection in the C shell

  • Piping Links any number of commands together to form a complex program. The standard output of one program becomes the standard input of the next. For more information, see the pipeline definition in Shells terminology.

  • Shell variable substitution Stores data in user-defined variables and predefined shell variables. For more information, see: – Parameter substitution in the Korn shell or POSIX shell – Variable substitution in the Bourne shell – Variable substitution in the C shell

Related concepts

Commands Some commands can be entered simply by typing one word. It is also possible to combine commands so that the output from one command becomes the input for another command.

Character classes

You can use character classes to match file names.

You can use character classes to match file names, as follows:

text
[[: charclass :]]

This format instructs the system to match any single character belonging to the specified class. The defined classes correspond to ctype subroutines, as follows:

  • alnum — Alphanumeric characters
  • alpha — Uppercase and lowercase letters
  • blank — Space or horizontal tab
  • cntrl — Control characters
  • digit — Digits
  • graph — Graphic characters
  • lower — Lowercase letters
  • print — Printable characters
  • punct — Punctuation characters
  • space — Space, horizontal tab, carriage return, newline, vertical tab, or form-feed character
  • upper — Uppercase characters
  • xdigit — Hexadecimal digits

Restricted shell

The restricted shell is used to set up login names and execution environments whose capabilities are more controlled than those of the regular Bourne shell.

The Rsh or bsh -r command opens the restricted shell. The behavior of these commands is identical to those of the bsh command, except that the following actions are not allowed:

  • Changing the directory (with the cd command)

  • Setting the value of PATH or SHELL variables

  • Specifying path or command names containing a slash (/)

  • Redirecting output

If the restricted shell determines that a command to be run is a shell procedure, it uses the Bourne shell to run the command. In this way, it is possible to provide a user with shell procedures that access the full power of the Bourne shell while imposing a limited menu of commands. This situation assumes that the user does not have write and execute permissions in the same directory.

If the File [Parameter] parameter is specified when the Bourne shell is started, the shell runs the script file identified by the File parameter, including any parameters specified. The script file specified must have read permission. Any setuid and setgid settings for script files are ignored. The shell then reads the commands. If either the -c or -s flag is used, do not specify a script file.

When started with the Rsh command, the shell enforces restrictions after interpreting the .profile and /etc/environment files. Therefore, the writer of the .profile file has complete control over user actions by performing setup actions and leaving the user in an appropriate directory (probably not the login directory). An administrator can create a directory of commands in the /usr/rbin directory that the Rsh

command can use by changing the PATH variable to contain the directory. If it is started with the bsh -r command, the shell applies restrictions when interpreting the .profile files.

When called with the name Rsh, the restricted shell reads the user's .profile file ($HOME/.profile). It acts as the regular Bourne shell while doing this, except that an interrupt causes an immediate exit instead of a return to command level.

The Korn shell can be started as a restricted shell with the command ksh -r.

The inodes for ksh and rksh are identical, and the inodes for ksh93 and rksh93 are identical.

Creating and running a shell script

A shell script is a file that contains one or more commands. Shell scripts provide an easy way to carry out tedious commands, large or complicated sequences of commands, and routine tasks. When you enter the name of a shell script file, the system executes the command sequence contained by the file.

You can create a shell script by using a text editor. Your script can contain both operating system commands and shell built-in commands.

The following steps are general guidelines for writing shell scripts:

  1. Using a text editor, create and save a file. You can include any combination of shell and operating system commands in the shell script file. By convention, shell scripts that are not set up for use by many users are stored in the $HOME/bin directory.

Note: The operating system does not support the setuid or setgid subroutines within a shell script.

  1. Use the chmod command to allow only the owner to run (or execute) the file. For example, if your file is named script1, type the following:
text
chmod u=rwx script1
  1. Type the script name on the command line to run the shell script. To run the script1 shell script, type the following:
text
script1

Note: You can run a shell script without making it executable if a shell command (ksh, bsh, or csh) precedes the shell script file name on the command line. For example, to run a nonexecutable file named script1 under the control of the Korn shell, type the following:

text
ksh script1

Related concepts

Commands Some commands can be entered simply by typing one word. It is also possible to combine commands so that the output from one command becomes the input for another command.