[AIX 운영 체제와 장치 관리 26] C 셸 (2) — C 셸 명령과 내장 명령 설명, 식과 연산자, 명령 치환, 기록 치환, 입출력 방향 바꾸기, 흐름 제어

핵심 정리

  • 셸 스크립트 첫 줄이 #!/ShellPathname이 아니면 C 셸은 기본 셸(/usr/bin/sh)로 스크립트를 실행하므로 C 셸 내장 명령을 쓰려면 #!/usr/bin/csh로 시작합니다.
  • 내장 명령은 셸 안에서 실행되지만 파이프라인의 마지막이 아닌 자리에 오면 서브셸에서 실행됩니다. limit 값의 배율은 k(기본)·m·b이고 CPU 시간은 hh:mm:ss입니다. nice 기본 우선순위는 24입니다.
  • @와 exit·if·while은 C 언어와 같은 우선순위의 식을 쓰며, =~·!~로 패턴 비교, -r·-w·-x·-e·-o·-z·-f·-d로 파일을 조회합니다. 0으로 시작하는 문자열은 8진수입니다.
  • 기록 참조는 Event[.]Word:Modifier 꼴이며 !!, !n, !-n, !str, !?str?, 단어 지정자(^, $, *, x-y)와 수정자(h, r, e, t, s, g, p, q, x)를 씁니다. 줄 처음의 ^old^new는 빠른 치환입니다.
  • 방향 바꾸기는 <, <<, >, >!, >&, >&!, >> 계열이며 >&는 표준 출력과 오류를 함께 보내고, noclobber를 무시하려면 ! 형식을 씁니다.
항목 내용
버전 AIX 6.1 (5.3판과 거의 같음)
원문 Operating system and device management — 5.3판 455474쪽(앞부분과 섞여 있음), 6.1판 274285쪽
관련 명령어 csh, alias, chdir, foreach, if, switch, limit, nice, nohup, onintr, pushd, popd, set, setenv, source, time, @
관련 파일 /etc/security/limits, /usr/include/sys/signal.h, .cshrc

단순 명령은 공백이나 탭으로 구분한 단어의 연속입니다. 단어는 따옴표 없는 공백을 포함하지 않는 문자나 숫자, 또는 둘 다의 연속입니다.

또 다음 문자와 겹문자는 명령 구분자나 종결자로 쓰일 때 하나의 단어가 됩니다.

text
&              ;

이 특수 문자는 다른 단어의 일부일 수 있습니다. 그러나 앞에 백슬래시(\)를 붙이면 셸이 특수 문자로 해석하지 않습니다. ' '나 " "(짝이 맞는 따옴표 쌍)나 역따옴표로 감싼 문자열도 단어의 일부가 될 수 있습니다. 이 기호로 감싸면 공백, 탭 문자, 특수 문자는 별도 단어가 되지 않습니다. 또 앞에 백슬래시(\)를 붙이면 이 기호 안에 줄 바꿈 문자를 넣을 수 있습니다.

단순 명령 순서의 첫 단어(번호 0)는 보통 명령 이름을 지정합니다. 나머지 단어는 몇 가지 예외를 빼고 그 명령에 넘어갑니다. 명령이 컴파일된 프로그램인 실행 파일을 지정하면 셸은 바로 그 프로그램을 실행합니다. 파일이 실행 가능하게 표시돼 있지만 컴파일된 프로그램이 아니면 셸 스크립트로 봅니다. 이때 셸은 자신의 또 다른 인스턴스(서브셸)를 시작해 파일을 읽고 그 안의 명령을 실행합니다.

C 셸 내장 명령

내장 명령은 셸 안에서 실행됩니다. 내장 명령이 파이프라인의 마지막이 아닌 구성 요소로 나오면 서브셸에서 실행됩니다.

참고: C 셸 프롬프트에서 명령을 입력하면 시스템은 먼저 내장 명령을 찾습니다. 내장 명령이 없으면 path 셸 변수로 지정한 디렉터리에서 시스템 수준 명령을 찾습니다. 어떤 C 셸 내장 명령과 운영 체제 명령은 이름이 같습니다. 그러나 반드시 똑같이 동작하지는 않습니다. 명령이 어떻게 동작하는지는 해당 명령 설명을 봅니다.

셸에서 셸 스크립트를 실행할 때 스크립트 첫 줄이 #!/ShellPathname으로 시작하면 C 셸은 주석에 지정한 셸로 스크립트를 처리합니다. 그렇지 않으면 기본 셸(/usr/bin/sh에 링크된 셸)을 실행합니다. 기본 셸이 실행하면 C 셸 내장 명령이 인식되지 않을 수 있습니다. C 셸 명령을 실행하려면 스크립트 첫 줄을 #!/usr/bin/csh로 합니다.

관련 참조

  • C 셸 내장 명령 목록

C 셸 명령 설명

C 셸은 다음 내장 명령을 제공합니다.

  • alias [Name [WordList]] — 매개변수를 지정하지 않으면 모든 별명을 보여 줍니다. 아니면 지정한 Name의 별명을 보여 줍니다. WordList를 지정하면 WordList 값을 별명 Name에 할당합니다. 별명 Name은 alias나 unalias일 수 없습니다.
  • bg [%Job ...] — 현재 작업이나 Job으로 지정한 작업을 백그라운드로 보내며, 멈춰 있으면 계속 실행합니다.
  • break — 가장 가까이 둘러싼 foreach나 while 명령의 end 뒤에서 실행을 이어갑니다.
  • breaksw — switch 명령에서 빠져나가 endsw 명령 뒤에서 이어갑니다.
  • case Label: — switch 명령의 Label을 정의합니다.
  • cd [Name] — chdir 명령과 같습니다(다음 설명 참고).
  • chdir [Name] — 현재 디렉터리를 Name으로 지정한 디렉터리로 바꿉니다. Name을 지정하지 않으면 홈 디렉터리로 바꿉니다. Name이 현재 디렉터리의 하위 디렉터리가 아니고 /, ./, ../로 시작하지 않으면 셸은 cdpath 셸 변수의 각 구성 요소에 Name과 맞는 하위 디렉터리가 있는지 확인합니다. Name이 슬래시(/)로 시작하는 값을 가진 셸 변수이면 그것이 디렉터리인지 확인합니다. chdir 명령은 cd 명령과 같습니다.
  • continue — 가장 가까이 둘러싼 while이나 foreach 명령의 end에서 실행을 계속합니다.
  • default: — switch 문의 default 경우에 레이블을 붙입니다. default는 다른 모든 case 레이블 뒤에 와야 합니다.
  • dirs — 디렉터리 스택을 보여 줍니다.
  • echo — 문자열을 셸의 표준 출력에 씁니다.
  • else — if (Expression) then ... else if (Expression2) then ... else ... endif 명령 순서에서 둘째 else 뒤의 명령을 실행합니다. 참고: else 문은 if (expr) then .. else ... endif를 쓸 때의 csh 내장 명령입니다. (expr)이 참이면 else 문까지의 명령을 실행합니다. (expr)이 거짓이면 else와 endif 사이의 명령을 실행합니다. 작은따옴표 안의 것은 글자 그대로 취급하고 해석하지 않습니다.
  • end — Name 변수를 List의 각 구성원으로 차례로 설정하고 foreach와 짝이 맞는 end 사이의 Commands를 실행합니다. foreach와 end 문은 각각 줄에 혼자 나와야 합니다. continue 문으로 반복을 계속하고 break 문으로 반복을 일찍 끝냅니다. 터미널에서 foreach 명령을 읽으면 C 셸은 Commands를 입력하도록 ?로 프롬프트를 냅니다. ? 프롬프트로 입력한 반복 안의 명령은 기록 목록에 넣지 않습니다.
  • endif — Expression이 참이면 첫 then 문 뒤의 Commands를 실행합니다. else if Expression2가 참이면 둘째 then 문 뒤의 Commands를 실행합니다. else if Expression2가 거짓이면 else 뒤의 Commands를 실행합니다. else if 쌍은 몇 개든 쓸 수 있습니다. endif 문은 하나만 있으면 됩니다. else 부분은 선택입니다. else와 endif 낱말은 입력 줄 처음에만 쓸 수 있습니다. if 부분은 입력 줄에 혼자 나오거나 else 명령 뒤에 나와야 합니다.
  • endsw — 각 case 레이블을 string 값과 차례로 맞춥니다. string은 먼저 명령과 파일 이름 펼치기를 거칩니다. case 레이블에는 패턴 일치 문자 *, ?, [...]를 쓰며 레이블은 변수 펼치기를 거칩니다. default 레이블을 만나기 전까지 맞는 레이블이 없으면 default 레이블 뒤에서 실행을 시작합니다. case 레이블과 default 레이블은 줄 처음에 나와야 합니다. breaksw 명령은 endsw 명령 뒤에서 실행을 이어가게 합니다. 그렇지 않으면 C 언어처럼 제어가 case와 default 레이블을 지나 아래로 흘러갈 수 있습니다. 맞는 레이블이 없고 default도 없으면 endsw 명령 뒤에서 실행을 이어갑니다.
  • eval Parameter ... — Parameter 값을 셸 입력으로 읽고 결과 명령을 현재 셸 문맥에서 실행합니다. 해석이 치환보다 먼저 일어나므로 명령이나 변수 치환의 결과로 만든 명령을 실행할 때 씁니다.
  • exec Command — 현재 셸 대신 지정한 Command를 실행합니다.
  • exit (Expression) — (Expression을 지정하지 않으면) status 셸 변수 값이나 지정한 Expression 값으로 셸을 끝냅니다.
  • fg [%Job ...] — 현재 작업이나 Job으로 지정한 작업을 포그라운드로 가져오며, 멈춰 있으면 계속 실행합니다.
  • foreach Name (List) Command ... — end 명령에 이를 때까지 List의 각 구성원마다 Name 변수를 차례로 설정하고 명령 순서를 실행합니다.
  • glob List — 기록, 변수, 파일 이름 펼치기를 해서 List를 보여 줍니다. 단어 사이에 널 문자를 넣고 끝에 캐리지 리턴을 넣지 않습니다.
  • goto Word — Word로 지정한 줄 뒤에서 실행을 이어갑니다. Word는 파일 이름과 명령 펼치기를 거쳐 Label: 꼴의 문자열이 됩니다. 셸은 입력을 되도록 되감고 앞에 공백이나 탭이 있을 수 있는 Label: 꼴의 줄을 찾습니다.
  • hashstat — 해시 표가 명령을 찾는 데 얼마나 성공했는지 보여 주는 통계를 보여 줍니다.
  • history [-r | -h] [n] — 기록 이벤트 목록을 보여 줍니다. 가장 오래된 이벤트부터 보여 줍니다. 숫자 n을 지정하면 가장 최근 이벤트 n개만 보여 줍니다. -r 플래그는 순서를 뒤집어 가장 최근 것부터 보여 줍니다. -h 플래그는 앞 번호 없이 기록 목록을 보여 줍니다. source 명령의 -h 플래그에 쓸 파일을 만들 때 씁니다.
  • if (Expression) Command — 지정한 Expression이 참이면 지정한 Command(인수 포함)를 실행합니다. Command의 변수 치환은 if 문의 나머지와 같은 때에 일찍 일어납니다. Command는 (파이프라인, 명령 목록, 괄호로 감싼 명령 목록이 아닌) 단순 명령이어야 합니다. 참고: Expression이 거짓이어서 Command를 실행하지 않아도 입출력 방향 바꾸기는 일어납니다.
  • jobs [-l] — 활성 작업을 나열합니다. -l(소문자 L) 플래그를 주면 작업 번호와 이름에 더해 프로세스 ID도 나열합니다.
  • kill -l, kill [-Signal] %Job..., kill [-Signal] PID... — 지정한 Job이나 PID(프로세스)에 TERM(종료) 신호나 Signal로 지정한 신호를 보냅니다. 신호는 번호나 (/usr/include/sys/signal.h 파일에 있는 이름에서 SIG 접두사를 뺀) 이름으로 지정합니다. -l(소문자 L) 플래그는 신호 이름을 나열합니다.
  • limit [-h] [Resource [Max-Use]] — 현재 프로세스와 그 프로세스가 만드는 각 프로세스의 지정한 자원 사용을 제한합니다. 프로세스 자원 한도는 /etc/security/limits 파일에 정의합니다. 제어할 수 있는 자원은 CPU 시간, 파일 크기, 데이터 크기, 코어 덤프 크기, 메모리 사용입니다. 이 자원의 최대 허용 값은 사용자를 시스템에 더할 때 mkuser 명령으로 설정하고 chuser 명령으로 바꿉니다. 한도는 소프트와 하드로 나뉩니다. 사용자는 하드 한도가 정한 상한까지 소프트 한도를 올릴 수 있습니다. 소프트 한도를 하드 한도 위로 올리거나 하드 한도를 바꾸려면 root 사용자 권한이 있어야 합니다. -h 플래그는 소프트 한도 대신 하드 한도를 보여 줍니다. Max-Use를 지정하지 않으면 지정한 자원의 현재 한도를 보여 줍니다. Resource를 지정하지 않으면 모든 자원의 현재 한도를 보여 줍니다. limit가 제어하는 자원에 관한 자세한 내용은 Technical Reference의 getrlimit, setrlimit, vlimit 서브루틴을 봅니다. CPU 시간의 Max-Use는 hh:mm:ss 형식으로 지정합니다. 다른 자원의 Max-Use는 부동소수점 수나 정수로 지정하며 뒤에 배율을 붙일 수 있습니다. 배율은 k(킬로바이트, 1024바이트), m(메가바이트), b(블록, ulimit 서브루틴이 쓰는 단위)입니다. 배율을 지정하지 않으면 모든 자원에 k를 씁니다. 자원 이름과 배율 모두 모호하지 않은 접두사면 충분합니다. 참고: 이 명령은 다른 활성 프로세스와 시스템 메모리를 두고 다툴 때만 프로세스가 쓸 수 있는 물리 메모리(메모리 사용)를 제한합니다.
  • login — 로그인 셸을 끝내고 /usr/bin/login 명령의 인스턴스로 바꿉니다. 로그아웃하는 방법 가운데 하나입니다(ksh와 bsh 명령과의 호환을 위해 포함).
  • logout — 로그인 셸을 끝냅니다. ignoreeof 옵션이 설정돼 있으면 이 명령을 써야 합니다.
  • nice [+n] [Command] — 값을 지정하지 않으면 이 셸에서 실행하는 명령의 우선순위를 24로 설정합니다. +n을 지정하면 우선순위에 지정한 수를 더합니다. +n과 Command를 지정하면 Command를 우선순위 24에 지정한 수를 더한 값으로 실행합니다. root 사용자 권한이 있으면 음수로 nice 문을 실행할 수 있습니다. Command는 늘 서브셸에서 실행되며 단순 if 문의 명령에 대한 제약이 적용됩니다.
  • nohup [Command] — Command를 지정하지 않으면 스크립트의 나머지 동안 hangup을 무시하게 합니다. Command를 지정하면 hangup을 무시한 채 Command를 실행합니다. 파이프라인이나 명령 목록을 실행하려면 셸 스크립트에 넣고 실행 권한을 준 뒤 그 스크립트를 Command 값으로 씁니다. 앰퍼샌드(&)로 백그라운드에서 실행한 모든 프로세스는 로그아웃할 때 hangup 신호를 받지 않도록 사실상 보호됩니다. 그러나 nohup 문을 쓰지 않으면 명시적으로 보낸 hangup은 여전히 받습니다.
  • notify [%Job...] — 현재 작업이나 지정한 Job의 상태가 바뀌면 셸이 비동기로 알리게 합니다. 보통 셸은 셸 프롬프트를 보여 주기 직전에 알립니다. notify 셸 변수가 설정돼 있으면 자동입니다.
  • onintr [- | Label] — 인터럽트에 대한 셸의 동작을 제어합니다. 인수가 없으면 셸 스크립트를 끝내거나 명령 입력 수준으로 돌아가는 기본 동작을 되살립니다. - 플래그를 지정하면 모든 인터럽트를 무시합니다. Label을 지정하면 셸이 인터럽트를 받거나 자식 프로세스가 인터럽트로 끝날 때 goto Label 문을 실행합니다. 어떤 경우든 셸이 분리돼 실행 중이고 인터럽트를 무시하고 있으면 onintr 문의 모든 형식은 의미가 없습니다. 셸과 호출한 모든 명령은 계속 인터럽트를 무시합니다.
  • popd [+n] — 디렉터리 스택을 꺼내고 새 맨 위 디렉터리로 바꿉니다. +n을 지정하면 스택의 n번째 항목을 버립니다. 디렉터리 스택 원소는 맨 위부터 0번으로 번호를 매깁니다.
  • pushd [+n | Name] — 인수가 없으면 디렉터리 스택의 맨 위 두 원소를 맞바꿉니다. Name을 주면 새 디렉터리로 바꾸고 이전 현재 디렉터리(cwd 셸 변수)를 디렉터리 스택에 넣습니다. +n을 지정하면 디렉터리 스택의 n번째 구성 요소를 맨 위 원소가 되도록 돌리고 그리로 바꿉니다. 디렉터리 스택 구성원은 맨 위부터 0번으로 번호를 매깁니다.
  • rehash — path 셸 변수의 디렉터리 내용을 담은 내부 해시 표를 다시 계산하게 합니다. 로그인해 있는 동안 path 셸 변수의 디렉터리에 새 명령을 더하면 필요합니다. 사용자 자신의 디렉터리에 명령을 더했거나 누군가 시스템 디렉터리의 내용을 바꿨을 때만 rehash 명령이 필요합니다.
  • repeat Count Command — 단순 if 문의 명령과 같은 제약 아래 지정한 Command를 Count번 실행합니다. 참고: Count가 0이어도 입출력 방향 바꾸기는 정확히 한 번 일어납니다.
  • set [[Name[n]] [= Word]], set [Name = (List)] — 인수 없이 쓰면 모든 셸 변수의 값을 보여 줍니다. 값이 단어 하나보다 많은 변수는 괄호로 감싼 단어 목록으로 보여 줍니다. Name만 지정하면 Name 변수를 빈 문자열로 설정합니다. 아니면 Name을 Word 값으로 설정하거나 List로 지정한 단어 목록으로 설정합니다. n을 지정하면 Name 변수의 n번째 구성 요소를 Word 값으로 설정하며, n번째 구성 요소가 이미 있어야 합니다. 어떤 경우든 값은 명령과 파일 이름 펼치기를 거칩니다. set 명령 하나에서 이 인수를 반복해 여러 값을 설정할 수 있습니다. 그러나 설정을 하기 전에 모든 인수의 변수 펼치기가 먼저 일어납니다.
  • setenv Name Value — Name으로 지정한 환경 변수 값을 문자열 하나인 Value로 설정합니다. 가장 흔히 쓰는 환경 변수 USER, TERM, HOME, PATH는 C 셸 변수 user, term, home, path와 자동으로 주고받으므로 setenv 문을 쓸 필요가 없습니다.
  • shift [Variable] — argv 셸 변수나 지정한 Variable의 구성원을 왼쪽으로 옮깁니다. argv 셸 변수나 지정한 Variable이 설정되지 않았거나 값이 한 단어보다 적으면 오류가 납니다.
  • source [-h] Name — Name 파일에 쓴 명령을 읽습니다. source 명령은 중첩할 수 있습니다. 그러나 너무 깊이 중첩하면 셸의 파일 기술자가 바닥날 수 있습니다. 어느 수준에서든 source 명령에 오류가 나면 중첩한 source 명령이 모두 끝납니다. 보통 source 명령 동안의 입력은 기록 목록에 넣지 않습니다. -h 플래그는 명령을 실행하지 않고 기록 목록에 넣습니다.
  • stop [%Job ...] — 백그라운드에서 실행 중인 현재 작업이나 지정한 Job을 멈춥니다.
  • suspend — STOP 신호를 받은 것처럼 셸을 멈춥니다.
  • switch (String) — switch (String) case String : ... breaksw default: ... breaksw endsw 명령 순서를 시작합니다. 각 case 레이블을 String 값과 차례로 맞춥니다. default 레이블을 만나기 전까지 맞는 레이블이 없으면 default 레이블 뒤에서 실행을 시작합니다.
  • time [Command] — 명령의 자동 시간 측정을 제어합니다. Command를 지정하지 않으면 이 셸과 그 자식이 쓴 시간 요약을 보여 줍니다. Command로 명령을 지정하면 그 명령의 시간을 잽니다. 그런 다음 time 셸 변수에서 설명한 대로 시간 요약을 보여 줍니다. 필요하면 명령이 끝날 때 시간 통계를 보여 주려고 셸을 하나 더 만듭니다. 다음 예는 time을 sleep 명령과 함께 씁니다. time sleep. 출력은 다음과 비슷합니다. 0.0u 0.0s 0:00 100% 44+4k 0+0io 0pf+0w. 출력 필드는 첫째 사용자 프로세스에 쓴 CPU 시간(초), 둘째 사용자 프로세스를 위해 커널이 쓴 CPU 시간(초), 셋째 명령의 경과(벽시계) 시간, 넷째 경과 시간에 대한 사용자 CPU 시간과 시스템 시간 합계의 백분율, 다섯째 공유 메모리 평균 사용량에 비공유 데이터 공간 평균 사용량을 더한 값(KB), 여섯째 블록 입출력 연산 수, 일곱째 페이지 부재와 스와프 수입니다.
  • umask [Value] — 파일 권한을 정합니다. 이 Value는 만드는 프로세스의 권한과 함께 파일을 만들 때 파일 권한을 정합니다. 기본값은 022입니다. Value를 지정하지 않으면 현재 설정을 보여 줍니다.
  • unalias *, unalias Pattern — 이름이 Pattern과 맞는 별명을 모두 버립니다. unalias * 명령은 모든 별명을 지웁니다. 별명이 없어도 오류가 아닙니다.
  • unhash — 실행할 프로그램을 찾는 데 내부 해시 표를 쓰지 않게 합니다.
  • unlimit [-h] [Resource] — Resource의 제한을 없앱니다. Resource를 지정하지 않으면 모든 자원 제한을 없앱니다. Resource 이름 목록은 limit 명령 설명을 봅니다. -h 플래그는 해당 하드 한도를 없앱니다. root 사용자 권한이 있는 사용자만 하드 한도를 바꿀 수 있습니다.
  • unset *, unset Pattern — 이름이 Pattern과 맞는 변수를 모두 지웁니다. 모든 변수를 지우려면 unset *를 씁니다. 설정된 변수가 없어도 오류가 아닙니다.
  • unsetenv Pattern — 이름이 지정한 Pattern과 맞는 변수를 환경에서 모두 지웁니다(setenv 내장 명령을 봅니다).
  • wait — 모든 백그라운드 작업을 기다립니다. 셸이 대화식이면 INTERRUPT(보통 Ctrl-C)가 기다림을 끊습니다. 그러면 셸은 아직 끝나지 않은 것으로 아는 모든 작업의 이름과 작업 번호를 보여 줍니다.
  • while (Expression) Command ... end — Expression으로 지정한 식이 0이 아닌 동안 while과 짝이 맞는 end 사이의 Commands를 평가합니다. break 문으로 반복을 일찍 끝내고 continue 문으로 계속할 수 있습니다. while과 end 문은 각각 입력 줄에 혼자 나와야 합니다. 입력이 터미널에서 오면 foreach 문처럼 while (Expression) 뒤에 프롬프트가 나옵니다.
  • @ [Name[n] = Expression] — 인수 없이 쓰면 모든 셸 변수의 값을 보여 줍니다. 아니면 Name으로 지정한 이름을 Expression 값으로 설정합니다. 식에 <, >, &, | 문자가 있으면 식의 그 부분을 괄호 안에 넣어야 합니다. n을 지정하면 Name 변수의 n번째 구성 요소를 Expression으로 설정합니다. Name 변수와 그 n번째 구성 요소가 이미 있어야 합니다. *=와 += 같은 C 언어 연산자를 쓸 수 있습니다. Name과 할당 연산자 사이의 공백은 선택입니다. 그러나 Expression의 구성 요소 사이에는 공백이 필요하며, 없으면 한 단어로 읽힙니다. 특수 접미 연산자 이중 더하기(++)와 이중 하이픈(--)은 각각 Name 변수 값을 늘리고 줄입니다.

C 셸 식과 연산자

@ 내장 명령과 exit, if, while 문은 C 언어와 비슷하고 우선순위도 같은 연산자를 포함한 식을 받습니다.

다음 연산자를 쓸 수 있습니다.

  • () — 우선순위 바꾸기
  • ~ — 보수
  • ! — 부정
  • *, /, % — 곱하기, 나누기, 나머지
  • +, - — 더하기, 빼기
  • <<, >> — 왼쪽 시프트, 오른쪽 시프트
  • <=, >=, <, > — 관계 연산자
  • ==, !=, =~, !~ — 문자열 비교·패턴 일치
  • & — 비트 AND
  • ^ — 비트 배타적 OR
  • | — 비트 포함 OR
  • && — 논리 AND
  • || — 논리 OR

이 목록에서 연산자 우선순위는 아래로 갈수록(왼쪽에서 오른쪽, 위에서 아래) 낮아집니다.

참고: 연산자 +와 -는 오른쪽 결합입니다. 예를 들어 a + b - c는 다음과 같이 평가하며

text
a + (b - c)

다음과 같이 평가하지 않습니다.

text
(a + b) - c

==, !=, =~, !~ 연산자는 인수를 문자열로 비교하고 나머지는 모두 수로 연산합니다. =~와 !~ 연산자는 ==, !=와 비슷하지만 오른쪽이 패턴이고 왼쪽 피연산자를 그 패턴과 맞춥니다. 그래서 셸 프로시저에서 switch 문을 쓸 필요가 줄어듭니다.

논리 연산자 or(||)와 and(&&)도 쓸 수 있습니다. 다음 예처럼 수의 범위를 확인하는 데 쓸 수 있습니다.

text
if ($#argv > 2 && $#argv < 7) then

앞 예에서 인수 수는 2보다 크고 7보다 작아야 합니다.

0으로 시작하는 문자열은 8진수로 봅니다. 비어 있거나 빠진 인수는 0으로 봅니다. 모든 식의 결과는 십진수를 나타내는 문자열입니다. 식의 두 구성 요소가 같은 단어에 나올 수 있다는 점에 주의합니다. 해석기에 구문상 의미가 있는 식 구성 요소(&, |, <, >, (, )) 옆이 아니면 식 구성 요소는 공백으로 둘러싸야 합니다.

식의 기본 피연산자로 괄호 ( )로 감싼 명령 실행과 (-operator Filename) 꼴의 파일 조회도 쓸 수 있으며, operator는 다음 가운데 하나입니다.

연산자 조회 내용
r 읽기 접근
w 쓰기 접근
x 실행 접근
e 존재
o 소유
z 크기 0
f 일반 파일
d 디렉터리

지정한 Filename은 명령과 파일 이름 펼치기를 거친 뒤 실제 사용자와 지정한 관계가 있는지 시험합니다. Filename이 없거나 접근할 수 없으면 모든 조회는 false(0)를 돌려줍니다. 명령이 성공하면 조회는 true(1)을 돌려줍니다. 명령이 실패하면 false(0)를 돌려줍니다. 더 자세한 상태 정보가 필요하면 식 밖에서 명령을 실행한 뒤 status 셸 변수를 살펴봅니다.

C 셸의 명령 치환

명령 치환에서 셸은 지정한 명령을 실행하고 그 명령을 출력으로 바꿉니다.

C 셸에서 명령 치환을 하려면 명령이나 명령 문자열을 역따옴표로 감쌉니다. 셸은 보통 명령의 출력을 공백, 탭, 줄 바꿈 문자에서 별도 단어로 나눕니다. 그런 다음 원래 명령을 이 출력으로 바꿉니다.

다음 예에서 date 명령을 감싼 역따옴표는 명령의 출력으로 치환한다는 뜻입니다.

text
echo The current date and time is: `date`

이 명령의 출력은 다음과 같을 수 있습니다.

text
The current date and time is: Wed Apr 8 13:52:14 CDT 1992

C 셸은 내장 셸 명령의 인수에 선택적으로 명령 치환을 합니다. 곧 평가하지 않는 식 부분은 펼치지 않습니다. 내장이 아닌 명령은 명령 이름을 인수 목록과 따로 치환합니다. 치환은 주 셸의 자식에서 일어나지만, 셸이 입출력 방향 바꾸기를 한 뒤에만 일어납니다.

명령 문자열을 " "로 감싸면 셸은 줄 바꿈 문자만 단어 구분자로 취급하므로 단어 안의 공백과 탭이 보존됩니다. 어떤 경우든 마지막 줄 바꿈 문자 하나는 새 단어를 만들지 않습니다.

관련 개념

  • C 셸의 변수 치환

내장이 아닌 C 셸 명령 실행

C 셸은 명령이 내장 셸 명령이 아니라고 판단하면 execv 서브루틴으로 명령을 실행하려 합니다.

path 셸 변수의 각 단어는 셸이 명령을 실행하려고 시도할 디렉터리를 가리킵니다. -c나 -t 플래그를 주지 않으면 셸은 이 디렉터리의 이름을 내부 표에 해시합니다. 셸은 명령이 그 디렉터리에 있을 가능성이 있을 때만 그 디렉터리에 execv 서브루틴을 호출합니다. unhash 명령으로 이 메커니즘을 끄거나 셸에 -c나 -t 플래그를 주면, 셸은 디렉터리와 주어진 명령 이름을 이어 붙여 파일 경로 이름을 만듭니다. 슬래시(/)로 시작하지 않는 path 변수의 디렉터리 구성 요소마다 셸은 어떤 경우든 이렇게 합니다. 그런 다음 명령을 실행하려 합니다.

괄호로 감싼 명령은 늘 서브셸에서 실행됩니다. 예를 들어 다음은

text
(cd ; pwd) ; pwd

현재 디렉터리 위치를 바꾸지 않고 홈 디렉터리를 보여 줍니다. 그러나 다음 명령은

text
cd ; pwd

현재 디렉터리 위치를 홈 디렉터리로 바꿉니다. 괄호로 감싼 명령은 chdir 명령이 현재 셸에 영향을 주지 않게 할 때 가장 자주 씁니다.

파일에 실행 권한이 있지만 시스템에서 실행 가능한 바이너리가 아니면, 셸은 셸 명령이 든 파일로 보고 새 셸을 실행해 읽습니다.

셸에 대한 별명이 있으면 별명의 단어를 인수 목록 앞에 붙여 셸 명령을 만듭니다. 별명의 첫 단어는 셸의 전체 경로 이름이어야 합니다.

C 셸의 기록 치환

기록 치환으로 이전 명령의 단어를 고쳐 새 명령을 만들 수 있습니다. 기록 치환을 쓰면 명령을 반복하거나, 이전 명령의 인수를 현재 명령에서 다시 쓰거나, 이전 명령의 철자 실수를 적은 입력으로 고칠 수 있습니다.

기록 치환은 느낌표(!) 문자로 시작하며, 중첩하지 않는 한(곧 기록 치환이 다른 기록 치환을 담지 않는 한) 명령행 어디에나 나올 수 있습니다. ! 앞에 \를 붙이면 느낌표의 특별한 뜻이 없어집니다. 또 !를 공백, 탭, 줄 바꿈 문자, =, ( 앞에 두면 기록 치환이 일어나지 않습니다.

입력 줄을 캐럿(^)으로 시작해도 기록 치환이 일어납니다. 셸은 기록 치환이 든 입력 줄을 실행하기 전에 워크스테이션에 에코합니다.

관련 개념

  • C 셸의 별명 치환

C 셸의 기록 목록

기록 목록은 셸이 명령행에서 읽은, 단어 하나 이상으로 된 명령을 저장합니다. 기록 치환은 저장한 명령의 단어 순서를 입력 흐름에 다시 넣습니다.

history 셸 변수가 기록 목록 크기를 정합니다. history 셸 변수는 .cshrc 파일에서나 명령행에서 내장 set 명령으로 설정해야 합니다. history 변수 값과 관계없이 이전 명령은 늘 유지합니다. 기록 목록의 명령은 1부터 차례로 번호가 매겨집니다. 내장 history 명령은 다음과 비슷한 출력을 냅니다.

text
9 write michael
10 ed write.c
11 cat oldwrite.c
12 diff *write.c

셸은 명령 문자열을 이벤트 번호와 함께 보여 줍니다. 이벤트 번호는 명령 왼쪽에 나오며, 기록의 다른 명령과 비교해 그 명령을 입력한 때를 나타냅니다. 보통 이벤트를 가리키려고 이벤트 번호를 쓸 필요는 없지만, PROMPT 환경 변수(원문 그대로, prompt 셸 변수)에 할당한 프롬프트 문자열에 느낌표(!)를 넣으면 시스템 프롬프트에 현재 이벤트 번호를 보여 줄 수 있습니다.

완전한 기록 참조는 다음 일반 형식으로 이벤트 지정, 단어 지정자, 수정자 하나 이상으로 이루어집니다.

text
Event[.]Word:Modifier[:Modifier] . . .

참고: 단어는 하나만 수정할 수 있습니다. 공백이 든 문자열은 허용하지 않습니다.

앞의 history 명령 출력 예에서 현재 이벤트 번호는 13입니다. 이 예로 다음은 이전 이벤트를 가리킵니다.

참조 가리키는 이벤트
!10 이벤트 번호 10
!-2 이벤트 번호 11(현재 이벤트에서 2를 뺀 것)
!d d로 시작하는 명령 단어(이벤트 번호 12)
!?mic? 문자열 mic가 든 명령 단어(이벤트 번호 9)

이 형식은 더 수정하지 않으면 지정한 이벤트의 단어를 스페이스 하나로 구분해 다시 넣기만 합니다. 특수한 경우로 !!는 이전 명령을 가리키며, 입력 줄에 !!만 있으면 이전 명령을 다시 실행합니다.

C 셸의 이벤트 지정

이벤트에서 단어를 고르려면 이벤트 지정 뒤에 콜론(:)과 다음 단어 지정자 가운데 하나를 둡니다(입력 줄의 단어는 0부터 차례로 번호가 매겨집니다).

지정자 고르는 단어
0 첫 단어(명령 이름)
n n번째 인수
^ 첫 인수
$ 마지막 인수
% 바로 앞의 ?string? 검색과 맞은 단어
x-y x번째 단어부터 y번째 단어까지의 범위
-y 첫 단어(0)부터 y번째 단어까지의 범위
* 첫 인수부터 마지막 인수까지. 이벤트에 단어가 하나(명령 이름)뿐이면 없음
x* x번째 인수부터 마지막 인수까지
x- x*와 같지만 마지막 인수를 뺌

단어 지정자가 ^, $, *, -, %로 시작하면 이벤트 지정과 단어 지정자를 구분하는 콜론을 생략할 수 있습니다. 선택 단어 지정자 뒤에 각각 콜론을 앞세운 다음 수정자를 차례로 둘 수도 있습니다.

수정자 동작
h 뒤쪽 경로 이름 구성 요소를 지우고 머리를 남깁니다.
r 뒤쪽 .xxx 구성 요소를 지우고 뿌리 이름을 남깁니다.
e 뒤쪽 .xxx 확장자만 남기고 모두 지웁니다.
s/OldWord/NewWord/ OldWord 값을 NewWord 값으로 바꿉니다.

치환의 왼쪽은 편집기가 인식하는 문자열이라는 뜻의 패턴이 아니라 단어, 곧 공백 없는 한 단위입니다. 보통 슬래시(/)가 원래 단어(OldWord)와 바꿀 단어(NewWord)를 구분합니다. 그러나 아무 문자나 구분자로 쓸 수 있습니다. 다음 예에서는 %를 구분자로 써서 단어에 /를 넣을 수 있습니다.

text
s%/home/myfile%/home/yourfile%

셸은 NewWord 안의 앰퍼샌드(&)를 OldWord 텍스트로 바꿉니다. 다음 예에서 /home/myfile은 /temp/home/myfile이 됩니다.

text
s%/home/myfile%/temp&%

셸은 치환의 빈 단어를 마지막 치환이나 문맥 검색 !?String?에 쓴 마지막 문자열로 바꿉니다. 바로 뒤에 줄 바꿈 문자가 오면 끝 구분자(/)를 생략할 수 있습니다. 다음 수정자로 기록 목록을 다룹니다.

수정자 동작
t 앞쪽 경로 이름 구성 요소를 모두 지우고 꼬리를 남깁니다.
& 앞의 치환을 반복합니다.
g 변경을 전체에, 곧 각 줄의 모든 일치에 적용합니다.
p 새 명령을 보여 주지만 실행하지 않습니다.
q 치환한 단어를 따옴표 처리해 이후 치환을 막습니다.
x q 수정자처럼 동작하지만 공백, 탭, 줄 바꿈 문자에서 단어로 나눕니다.

이 수정자를 쓰면 g 수정자가 앞에 오지 않는 한 변경은 첫 번째 수정 가능한 단어에만 적용됩니다.

이벤트 지정 없이 기록 참조(예: !$)를 주면 셸은 이전 명령을 이벤트로 씁니다. 같은 줄에 앞선 기록 참조가 있으면 셸은 그 참조를 반복합니다. 그래서 다음 순서는 ?foo?와 맞는 명령의 첫 인수와 마지막 인수를 줍니다.

text
!?foo?^ !$

입력 줄의 첫 공백 아닌 문자가 캐럿(^)이면 기록 참조의 특수 줄임이 됩니다. 이것은 !:s^와 같아서 이전 줄 텍스트에 대한 치환을 편하게 줄여 씁니다. ^lb^lib 명령은 명령에서 lib의 철자를 고칩니다.

필요하면 기록 치환을 중괄호 { }로 감싸 뒤따르는 문자와 떼어 놓을 수 있습니다. 예를 들어 다음 명령에 대한 참조를

text
ls -ld ~paul

써서 다음 명령을 실행하려면

text
ls -ld ~paula

다음 구문을 씁니다.

text
!{l}a

이 예에서 !{l}a는 l로 시작하는 명령을 찾아 끝에 a를 붙입니다.

작은따옴표와 큰따옴표로 감싸기

치환의 전부나 일부를 더 해석하지 않게 하려면 문자열을 작은따옴표나 큰따옴표로 감쌉니다.

문자열을 ' '로 감싸면 더 해석하지 않고, " "로 감싸면 더 펼칠 수 있습니다. 두 경우 모두 결과 텍스트는 한 단어의 전부나 일부가 됩니다.

C 셸의 입출력 방향 바꾸기

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

다음 구문으로 명령의 표준 입력과 출력의 방향을 바꿀 수 있습니다.

  • < File — (먼저 변수, 명령, 파일 이름 펼치기를 거친) 지정한 File을 표준 입력으로 엽니다.
  • << Word — Word 값과 맞는 줄까지 셸 입력을 읽습니다. Word는 변수, 파일 이름, 명령 치환을 거치지 않습니다. 각 입력 줄은 줄에 치환을 하기 전에 Word와 비교합니다. Word에 따옴표 문자(\, ", ', 역따옴표)가 없으면 셸은 사이의 줄에 변수와 명령 치환을 하며, \ 문자로 $, \, 역따옴표 문자를 따옴표 처리할 수 있습니다. 치환한 명령은 마지막 줄 바꿈 문자(버림)를 빼고 모든 공백, 탭, 줄 바꿈 문자를 보존합니다. 결과 텍스트는 이름 없는 임시 파일에 넣어 명령의 표준 입력으로 줍니다.
  • > File, >! File, >& File, >&! File — 지정한 File을 표준 출력으로 씁니다. File이 없으면 만듭니다. 있으면 길이를 자르고 이전 내용을 잃습니다. noclobber 셸 변수가 설정돼 있으면 File이 없거나 문자 특수 파일이어야 하며, 아니면 오류가 납니다. 이렇게 해서 파일이 실수로 지워지는 것을 막습니다. 이때 이 검사를 건너뛰려면 !가 든 형식을 씁니다. File은 < 입력 파일 이름과 같은 방식으로 펼칩니다. >& 형식은 표준 출력과 표준 오류를 모두 지정한 File로 보냅니다. 다음 예는 표준 출력을 /dev/tty로, 표준 오류를 /dev/null로 따로 보내는 방법을 보여 줍니다. 표준 출력과 표준 오류를 나누려면 괄호가 필요합니다. % (find / -name vi -print > /dev/tty) >& /dev/null
  • >> File, >>! File, >>& File, >>&! File — >처럼 지정한 File을 표준 출력으로 쓰되 출력을 File 끝에 덧붙입니다. noclobber 셸 변수가 설정돼 있으면 !가 든 형식을 쓰지 않는 한 File이 없을 때 오류가 납니다. 그 밖에는 >와 비슷합니다.

명령은 셸이 호출된 환경을 입출력 매개변수와 명령이 파이프라인에 있는지에 따라 바꾼 환경을 받습니다. 그래서 이전 일부 셸과 달리 셸 스크립트에서 실행한 명령은 기본적으로 명령 텍스트에 접근하지 못합니다. 대신 셸의 원래 표준 입력을 받습니다. 인라인 데이터를 주려면 << 메커니즘을 씁니다. 그러면 셸 명령 파일이 파이프라인의 구성 요소로 동작할 수 있고 셸이 입력을 블록 단위로 읽을 수 있습니다. 분리해 실행하는 명령의 기본 표준 입력은 빈 /dev/null 파일로 바뀌지 않고 셸의 원래 표준 입력으로 남는다는 점에 주의합니다.

표준 오류를 표준 출력과 함께 파이프로 보내려면 | 대신 |& 형식을 씁니다.

C 셸의 흐름 제어

셸에는 명령 파일(셸 스크립트)과 (제한적이지만 쓸모 있게) 셸 명령행 입력에서 제어 흐름을 조절하는 명령이 있습니다. 이 명령들은 모두 셸이 입력을 반복하거나 건너뛰게 해서 동작합니다.

foreach, switch, while 문과 if 문의 if-then-else 형식은 주요 키워드가 입력 줄의 단순 명령 하나 안에 나와야 합니다.

셸 입력을 검색할 수 없으면 셸은 반복을 읽을 때마다 입력을 버퍼에 담고 내부 버퍼를 검색해 반복에 필요한 다시 읽기를 합니다. 이것이 허용되는 범위에서 검색할 수 없는 입력에서도 뒤로 가는 goto가 성공합니다.

영어 원문

C shell commands

A simple command is a sequence of words separated by blanks or tabs. A word is a sequence of characters or numerals, or both, that does not contain blanks without quotation marks.

In addition, the following characters and doubled characters also form single words when used as command separators or terminators:

text
&              ;

These special characters can be parts of other words. Preceding them with a backslash (\), however, prevents the shell from interpreting them as special characters. Strings enclosed in ’ ’ or " " (matched pairs of quotation characters) or backquotes can also form parts of words. Blanks, tab characters, and special characters do not form separate words when they are enclosed in these marks. In addition, you can enclose a newline character within these marks by preceding it with a backslash (\).

The first word in the simple command sequence (numbered 0) usually specifies the name of a command. Any remaining words, with a few exceptions, are passed to that command. If the command specifies an executable file that is a compiled program, the shell immediately runs that program. If the file is marked executable but is not a compiled program, the shell assumes that it is a shell script. In this case, the shell starts another instance of itself (a subshell) to read the file and execute the commands included in it.

C shell built-in commands:

Built-in commands are run within the shell. If a built-in command occurs as any component of a pipeline, except the last, the command runs in a subshell.

Note: If you enter a command from the C shell prompt, the system searches for a built-in command first. If a built-in command does not exist, the system searches the directories specified by the path shell variable for a system-level command. Some C shell built-in commands and operating system commands

have the same name. However, these commands do not necessarily work the same way. For more information on how the command works, check the appropriate command description.

If you run a shell script from the shell, and the first line of the shell script begins with #!/ShellPathname, the C shell runs the shell specified in the comment to process the script. Otherwise, it runs the default shell (the shell linked to /usr/bin/sh). If run by the default shell, C shell built-in commands might not be recognized. To run C shell commands, make the first line of the script #!/usr/bin/csh.

Related reference

C shell built-in commands list The following are C shell built-in commands.

C shell command descriptions:

The C shell provides the following built-in commands.

  • alias [Name [WordList]] — Displays all aliases if you do not specify any parameters. Otherwise, the command displays the alias for the specified Name. If WordList is specified, this command assigns the value of WordList to the alias Name. The specified alias Name cannot be alias or unalias.
  • bg [%Job ...] — Puts the current job or job specified by Job into the background, continuing the job if it was stopped.
  • break — Resumes running after the end of the nearest enclosing foreach or while command.
  • breaksw — Breaks from a switch command; resumes after the endsw command.
  • case Label: — Defines a Label in a switch command.
  • cd[Name] — Equivalent to the chdir command (see following description).
  • chdir [Name] — Changes the current directory to that specified by the Name variable. If you do not specify Name, the command changes to your home directory. If the value of the Name variable is not a subdirectory of the current directory and does not begin with /, ./, or ../, the shell checks each component of the cdpath shell variable to see if it has a subdirectory matching the Name variable. If the Name variable is a shell variable with a value that begins with a slash (/), the shell tries this to see if it is a directory. The chdir command is equivalent to the cd command.
  • continue — Continues execution at the end of the nearest enclosing while or foreach command.
  • default: — Labels the default case in a switch statement. The default should come after all other case labels.
  • dirs — Displays the directory stack.
  • echo — Writes character strings to the standard output of the shell.
  • else — Runs the commands that follow the second else in an if (Expression) then ...else if (Expression2) then ... else ... endif command sequence. Note: The else statement is the csh built-in command when using the if(expr) then ..else ...endif. If the (expr) is true, then the commands up to the else statement is executed. If the (expr) is false, then the commands between the else and endif statement are executed. Anything in single quotes is taken literally and not interpreted.
  • end — Successively sets the Name variable to each member specified by the List variable and runs the sequence of Commands between the foreach and the matching end statements. The foreach and end statements must appear alone on separate lines. Uses the continue statement to continue the loop and the break statement to end the loop prematurely. When the foreach command is read from the terminal, the C shell prompts with a ? to allow Commands to be entered. Commands within loops, prompted for by ?, are not placed in the history list.
  • endif — If the Expression variable is true, runs the Commands that follow the first then statement. If the else if Expression2 is true, runs the Commands that follow the second then statement. If the else if Expression2 is false, runs the Commands that follow the else. Any number of else if pairs are possible. Only one endif statement is needed. The else segment is optional. The words else and endif can be used only at the beginning of input lines. The if segment must appear alone on its input line or after an else command.
  • endsw — Successively matches each case label against the value of the string variable. The string is command and file name expanded first. Use the pattern-matching characters *, ?, and [ . . . ] in the case labels, which are variable-expanded. If none of the labels match before a default label is found, the execution begins after the default label. The case label and the default label must appear at the beginning of the line. The breaksw command causes execution to continue after the endsw command. Otherwise, control might fall through the case and default labels, as in the C programming language. If no label matches and there is no default, execution continues after the endsw command.
  • eval Parameter . . . — Reads the value of the Parameter variable as input to the shell and runs the resulting command or commands in the context of the current shell. Use this command to run commands generated as the result of command or variable substitution because parsing occurs before these substitutions.
  • exec Command — Runs the specified Command in place of the current shell.
  • exit (Expression) — Exits the shell with either the value of the status shell variable (if no Expression is specified) or with the value of the specified Expression.
  • fg [%Job ...] — Brings the current job or job specified by Job into the foreground, continuing the job if it was stopped.
  • foreach Name (List) Command. . . — Successively sets a Name variable for each member specified by the List variable and a sequence of commands, until reaching an end command.
  • glob List — Displays List using history, variable, and file name expansion. Puts a null character between words and does not include a carriage return at the end.
  • goto Word — Continues to run after the line specified by the Word variable. The specified Word is file name and command expanded to yield a string of the form specified by the Label: variable. The shell rewinds its input as much as possible and searches for a line of the form Label:, possibly preceded by blanks or tabs.
  • hashstat — Displays statistics indicating how successful the hash table has been at locating commands.
  • history [-r | -h] [n] — Displays the history event list. The oldest events are displayed first. If you specify a number n, only the specified number of the most recent events are displayed. The -r flag reverses the order in which the events are displayed so the most recent is displayed first. The -h flag displays the history list without leading numbers. Use this flag to produce files suitable for use with the -h flag of the source command.
  • if (Expression) Command — Runs the specified Command (including its arguments) if the specified Expression is true. Variable substitution on the Command variable happens early, at the same time as the rest of the if statement. The specified Command must be a simple command (rather than a pipeline, command list, or parenthesized command list). Note: Input and output redirection occurs even if the Expression variable is false and the Command is not executed.
  • jobs [-l] — Lists the active jobs. With the -l (lowercase L) flag, the jobs command lists process IDs in addition to the job number and name.
  • kill -l | [[-Signal] % Job...|PID...] — Sends either the TERM (terminate) signal or the signal specified by Signal to the specified Job or PID (process). Specify signals either by number or by name (as given in the /usr/include/sys/signal.h file, stripped of the SIG prefix). The -l (lowercase L) flag lists the signal names.
  • limit [-h] [Resource [Max-Use]] — Limits the usage of the specified resource by the current process and each process it creates. Process resource limits are defined in the /etc/security/limits file. Controllable resources are the central processing unit (CPU) time, file size, data size, core dump size, and memory use. Maximum allowable values for these resources are set with the mkuser command when the user is added to the system. They are changed with the chuser command. Limits are categorized as either soft or hard. Users may increase their soft limits up to the ceiling imposed by the hard limits. You must have root user authority to increase a soft limit above the hard limit, or to change hard limits. The -h flag displays hard limits instead of the soft limits. If a Max-Use parameter is not specified, the limit command displays the current limit of the specified resource. If the Resource parameter is not specified, the limit command displays the current limits of all resources. For more information about the resources controlled by the limit subcommand, see the getrlimit, setrlimit, or vlimit subroutine in the Technical Reference: Base Operating System and Extensions, Volume 1. The Max-Use parameter for CPU time is specified in the hh:mm:ss format. The Max-Use parameter for other resources is specified as a floating-point number or an integer optionally followed by a scale factor. The scale factor is k or kilobytes (1024 bytes), m or megabytes, or b or blocks (the units used by the ulimit subroutine as explained in the Technical Reference: Base Operating System and Extensions, Volume 2). If you do not specify a scale factor, k is assumed for all resources. For both resource names and scale factors, unambiguous prefixes of the names suffice. Note: This command limits the physical memory (memory use) available for a process only if there is contention for system memory by other active processes.
  • login — Ends a login shell and replaces it with an instance of the /usr/bin/login command. This is one way to log out (included for compatibility with the ksh and bsh commands).
  • logout — Ends a login shell. This command must be used if the ignoreeof option is set.
  • nice [+n] [Command] — If no values are specified, sets the priority of commands run in this shell to 24. If the +n flag is specified, sets the priority plus the specified number. If the +n flag and Command are specified, runs Command at priority 24 plus the specified number. If you have root user authority, you can run the nice statement with a negative number. The Command always runs in a subshell, and the restrictions placed on commands in simple if statements apply.
  • nohup [Command] — Causes hangups to be ignored for the remainder of the script when no Command is specified. If Command is specified, causes the specified Command to be run with hangups ignored. To run a pipeline or list of commands, put the pipeline or list in a shell script, give the script execute permission, and use the shell script as the value of the Command variable. All processes run in the background with an ampersand (&) are effectively protected from being sent a hangup signal when you log out. However, these processes are still subject to explicitly sent hangups unless the nohup statement is used.
  • notify [%Job...] — Causes the shell to notify you asynchronously when the status of the current job or specified Job changes. Normally, the shell provides notification just before it presents the shell prompt. This feature is automatic if the notify shell variable is set.
  • onintr [- | Label] — Controls the action of the shell on interrupts. If no arguments are specified, restores the default action of the shell on interrupts, which ends shell scripts or returns to the command input level. If a - flag is specified, causes all interrupts to be ignored. If Label is specified, causes the shell to run a goto Label statement when the shell receives an interrupt or when a child process ends due to an interruption. In any case, if the shell is running detached and interrupts are being ignored, all forms of the onintr statement have no meaning. Interrupts continue to be ignored by the shell and all invoked commands.
  • popd [+n] — Pops the directory stack and changes to the new top directory. If you specify a +n variable, the command discards the nth entry in the stack. The elements of the directory stack are numbered from the top, starting at 0.
  • pushd [+``n|Name] — With no arguments, exchanges the top two elements of the directory stack. With the Name variable, the command changes to the new directory and pushes the old current directory (as given in the cwd shell variable) onto the directory stack. If you specify a +n variable, the command rotates the nth component of the directory stack around to be the top element and changes to it. The members of the directory stack are numbered from the top, starting at 0.
  • rehash — Causes recomputation of the internal hash table of the contents of the directories in the path shell variable. This action is needed if new commands are added to directories in the path shell variable while you are logged in. The rehash command is necessary only if commands are added to one of the user's own directories or if someone changes the contents of one of the system directories.
  • repeat Count Command — Runs the specified Command, subject to the same restrictions as commands in simple if statements, the number of times specified by Count. Note: I/O redirections occur exactly once, even if the Count variable equals 0.
  • set [[Name[n]] [ = Word]] | [Name = (List)] — Shows the value of all shell variables when used with no arguments. Variables that have more than a single word as their value are displayed as a parenthesized word list. If only Name is specified, the C shell sets the Name variable to the null string. Otherwise, sets Name to the value of the Word variable, or sets the Name variable to the list of words specified by the List variable. When n is specified, the nth component of the Name variable is set to the value of the Word variable; the nth component must already exist. In all cases, the value is command and file name expanded. These arguments may be repeated to set multiple values in a single set command. However, variable expansion happens for all arguments before any setting occurs.
  • setenvName Value — Sets the value of the environment variable specified by the Name variable to Value, a single string. The most commonly used environment variables, USER, TERM, HOME, and PATH, are automatically imported to and exported from the C shell variables user, term, home, and path. There is no need to use the setenv statement for these.
  • shift [Variable] — Shifts the members of the argv shell variable or the specified Variable to the left. An error occurs if the argv shell variable or specified Variable is not set or has less than one word as its value.
  • source[-h] Name — Reads commands written in the Name file. You can nest the source commands. However, if they are nested too deeply, the shell might run out of file descriptors. An error in a source command at any level ends all nested source commands. Normally, input during source commands is not placed on the history list. The -h flag causes the commands to be placed in the history list without executing them.
  • stop [%Job ...] — Stops the current job or specified Job running in the background.
  • suspend — Stops the shell as if a STOP signal had been received.
  • switch (string) — Starts a switch (String) case String : ... breaksw default: ... breaksw endsw command sequence. This command sequence successively matches each case label against the value of the String variable. If none of the labels match before a default label is found, the execution begins after the default label.
  • time [Command] — The time command controls automatic timing of commands. If you do not specify the Command variable, the time command displays a summary of time used by this shell and its children. If you specify a command with the Command variable, it is timed. The shell then displays a time summary, as described under the time shell variable. If necessary, an extra shell is created to display the time statistic when the command completes. The following example uses time with the sleep command: time sleep The output from this command looks similar to the following: 0.0u 0.0s 0:00 100% 44+4k 0+0io 0pf+0w The output fields are as follows: First Number of seconds of CPU time devoted to the user process Second Number of seconds of CPU time consumed by the kernel on behalf of the user process Third Elapsed (wall clock) time for the command Fourth Total user CPU Time plus system time, as a percentage of elapsed time Fifth Average amount of shared memory used, plus average amount of unshared data space used, in kilobytes Sixth Number of block input and output operations Seventh Page faults plus number of swaps
  • umask [Value] — Determines file permissions. This Value, along with the permissions of the creating process, determines a file's permissions when the file is created. The default is 022. The current setting will be displayed if no Value is specified.
  • unalias *|Pattern — Discards all aliases with names that match the Pattern variable. All aliases are removed by the unalias * command. The absence of aliases does not cause an error.
  • unhash — Disables the use of the internal hash table to locate running programs.
  • unlimit [-h][Resource] — Removes the limitation on the Resource variable. If no Resource variable is specified, all resource limitations are removed. See the description of the limit command for the list of Resource names. The -h flag removes corresponding hard limits. Only a user with root user authority can change hard limits.
  • unset *|Pattern — Removes all variables with names that match the Pattern variable. Use unset * to remove all variables. If no variables are set, it does not cause an error.
  • unsetenvPattern — Removes all variables from the environment whose name matches the specified Pattern. (See the setenv built-in command.)
  • wait — Waits for all background jobs. If the shell is interactive, an INTERRUPT (usually the Ctrl-C key sequence) disrupts the wait. The shell then displays the names and job numbers of all jobs known to be outstanding.
  • while (Expression) Command. . . end — Evaluates the Commands between the while and the matching end statements while the expression specified by the Expression variable evaluates nonzero. You can use the break statement to end and the continue statement to continue the loop prematurely. The while and end statements must appear alone on their input lines. If the input is from a terminal, prompts occur after the while (Expression) similar to the foreach statement.
  • @ [Name[n] = Expression] — Displays the values of all the shell variables when used with no arguments. Otherwise, sets the name specified by the Name variable to the value of the Expression variable. If the expression contains <, >, &, or | characters, this part of the expression must be placed within parentheses. When n is specified, the nth component of the Name variable is set to the Expression variable. Both the Name variable and its nth component must already exist. C language operators, such as *= and +=, are available. The space separating the Name variable from the assignment operator is optional. Spaces are, however, required in separating components of the Expression variable, which would otherwise be read as a single word. Special suffix operators, double plus sign (++) and double hyphen (--) increase and decrease, respectively, the value of the Name variable.
  • C shell expressions and operators:

The @ built-in command and the exit, if, and while statements accept expressions that include operators similar to those of C language, with the same precedence.

The following operators are available:

  • () — change precedence
  • ~ — complement
  • ! — negation
  • */ % — multiply, divide, modulo
  • + - — add, subtract
  • << > > — left shift, right shift
  • <= >= < > — relational operators
  • == != =~ !~ — string comparison/pattern matching
  • & — bitwise AND
  • ^ — bitwise exclusive OR bitwise inclusive OR
  • && — logical AND
  • || — logical OR

In the previous list, precedence of the operators decreases down the list (left to right, top to bottom).

Note: The operators + and - are right-associative. For example, evaluation of a + b - c is performed as follows:

text
a + (b - c)

and not as follows:

text
(a + b) - c

The ==, !=, =~, and !~ operators compare their arguments as strings; all others operate on numbers. The =~ and !~ operators are similar to == and != , except that the rightmost side is a pattern against which the leftmost operand is matched. This reduces the need for use of the switch statement in shell procedures.

The logical operators or (|``|) and and (&&) are also available. They can be used to check for a range of numbers, as in the following example:

text
if ($#argv > 2 && $#argv < 7) then

In the preceding example, the number of arguments must be greater than 2 and less than 7.

Strings beginning with zero (0) are considered octal numbers. Null or missing arguments are considered 0. All expressions result in strings representing decimal numbers. Note that two components of an

expression can appear in the same word. Except when next to components of expressions that are syntactically significant to the parser (& | < > ( )), expression components should be surrounded by spaces.

Also available in expressions as primitive operands are command executions enclosed in parentheses ( ) and file inquiries of the form (-operator Filename), where operator is one of the following:

  • r — Read access
  • w — Write access
  • x — Execute access
  • e — Existence
  • o — Ownership
  • z — Zero size
  • f — Plain file
  • d — Directory

The specified Filename is command and file name expanded and then tested to see if it has the specified relationship to the real user. If Filename does not exist or is inaccessible, all inquiries return false(0). If the command runs successfully, the inquiry returns a value of true(1). Otherwise, if the command fails, the inquiry returns a value of false(0). If more detailed status information is required, run the command outside an expression and then examine the status shell variable.

Command substitution in the C shell:

In command substitution, the shell executes a specified command and replaces that command with its output.

To perform command substitution in the C shell, enclose the command or command string in backquotes (' '). The shell normally breaks the output from the command into separate words at blanks, tabs, and newline characters. It then replaces the original command with this output.

In the following example, the backquotes (' ') around the date command indicate that the output of the command will be substituted:

text
echo The current date and time is: `date`

The output from this command might look like the following:

text
The current date and time is: Wed Apr 8 13:52:14 CDT 1992

The C shell performs command substitution selectively on the arguments of built-in shell commands. This means that it does not expand those parts of expressions that are not evaluated. For commands that are not built-in, the shell substitutes the command name separately from the argument list. The substitution occurs in a child of the main shell, but only after the shell performs input or output redirection.

If a command string is surrounded by " ", the shell treats only newline characters as word separators, thus preserving blanks and tabs within the word. In all cases, the single final newline character does not force a new word.

Related concepts

Variable substitution in the C shell The C shell maintains a set of variables, each of which has as its value a list of zero or more words. Some of these variables are set by the shell or referred to by it. For example, the argv variable is an image of the shell variable list, and words that comprise the value of this variable are referred to in special ways.

Nonbuilt-in C shell command execution:

When the C shell determines that a command is not a built-in shell command, it attempts to run the command with the execv subroutine.

Each word in the path shell variable names a directory from which the shell attempts to run the command. If given neither the -c nor -t flag, the shell hashes the names in these directories into an internal table. The shell tries to call the execv subroutine on a directory only if there is a possibility that the command resides there. If you turn off this mechanism with the unhash command or give the shell the -c or -t flag, the shell concatenates with the given command name to form a path name of a file. The shell also does this in any case for each directory component of the path variable that does not begin with a slash (/). The shell then attempts to run the command.

Parenthesized commands always run in a subshell. For example:

text
(cd ; pwd) ; pwd

displays the home directory without changing the current directory location. However, the command:

text
cd ; pwd

changes the current directory location to the home directory. Parenthesized commands are most often used to prevent the chdir command from affecting the current shell.

If the file has execute permission, but is not an executable binary to the system, then the shell assumes it is a file containing shell commands and runs a new shell to read it.

If there is an alias for the shell, then the words of the alias are prefixed to the argument list to form the shell command. The first word of the alias should be the full path name of the shell.

History substitution in the C shell

History substitution lets you modify individual words from previous commands to create new commands. History substitution makes it easy to repeat commands, repeat the arguments of a previous command in the current command, or fix spelling mistakes in the previous command with little typing.

History substitutions begin with the exclamation mark (!) character and can appear anywhere on the command line, provided they do not nest (in other words, a history substitution cannot contain another history substitution). You can precede the ! with a \ to cancel the exclamation point's special meaning. In addition, if you place the ! before a blank, tab, newline character, =, or (, history substitution does not occur.

History substitutions also occur when you begin an input line with a carat (^). The shell echoes any input line containing history substitutions at the workstation before it executes that line.

Related concepts

Alias substitution in the C shell An alias is a name assigned to a command or command string. The C shell allows you to assign aliases and use them as you would commands. The shell maintains a list of the aliases that you define.

History lists for the C shell:

The history list saves commands that the shell reads from the command line that consist of one or more words. History substitution reintroduces sequences of words from these saved commands into the input stream.

The history shell variable controls the size of the history list. You must set the history shell variable either in the .cshrc file or on the command line with the built-in set command. The previous command is

always retained regardless of the value of the history variable. Commands in the history list are numbered sequentially, beginning with 1. The built-in history command produces output similar to the following:

text
9 write michael
10 ed write.c
11 cat oldwrite.c
12 diff *write.c

The shell displays the command strings with their event numbers. The event number appears to the left of the command and represent when the command was entered in relation to the other commands in the history. It is not usually necessary to use event numbers to refer to events, but you can have the current event number displayed as part of your system prompt by placing an exclamation mark (!) in the prompt string assigned to the PROMPT environment variable.

A full history reference contains an event specification, a word designator, and one or more modifiers in the following general format:

text
Event[.]Word:Modifier[:Modifier] . . .

Note: Only one word can be modified. A string that contains blanks is not allowed.

In the previous sample of history command output, the current event number is 13. Using this example, the following refer to previous events:

  • !10 — Event number 10.
  • !-2 — Event number 11 (the current event minus 2).
  • !d — Command word beginning with d (event number 12).
  • !?mic? — Command word containing the string mic (event number 9).

These forms, without further modification, simply reintroduce the words of the specified events, each separated by a single blank. As a special case, !! refers to the previous command; the command !! alone on an input line reruns the previous command.

Event specification for the C shell:

To select words from an event, follow the event specification with a colon (:) and one of the following word designators (the words of an input line are numbered sequentially starting from 0)

  • 0 — First word (the command name)
  • n — nth argument
  • ^ — First argument
  • $ — Last argument
  • % — Word matched by an immediately preceding ?string? search
  • x-y — Range of words from the xth word to the yth word
  • -y — Range of words from the first word (0) to the yth word
  • * — First through the last argument, or nothing if there is only one word (the command name) in the event
  • x* — xth argument through the last argument
  • x- — Same as x* but omitting the last argument

If the word designator begins with a ^, $, *, -, or %, you can omit the colon that separates the event specification from the word designator. You can also place a sequence of the following modifiers after the optional word designator, each preceded by a colon:

  • h — Removes a trailing path name extension, leaving the head.
  • r — Removes a trailing .xxx component, leaving the root name.
  • e — Removes all but the .xxx trailing extension.
  • s/OldWord/NewWord/ — Substitutes the value of the NewWord variable for the value of the OldWord variable.

The left side of a substitution is not a pattern in the sense of a string recognized by an editor; rather, it is a word, a single unit without blanks. Normally, a slash (/) delimits the original word (OldWord) and its replacement (NewWord). However, you can use any character as the delimiter. In the following example, using the % as a delimiter allows a / to be included in the words:

text
s%/home/myfile%/home/yourfile%

The shell replaces an ampersand (&) with the OldWord text in the NewWord variable. In the following example, /home/myfile becomes /temp/home/myfile.

text
s%/home/myfile%/temp&%

The shell replaces a null word in a substitution with either the last substitution or with the last string used in the contextual scan !?String?. You can omit the trailing delimiter (/) if a newline character follows immediately. Use the following modifiers to delimit the history list:

  • t — Removes all leading path name components, leaving the tail
  • & — Repeats the previous substitution
  • g — Applies the change globally; that is, all occurrences for each line
  • p — Displays the new command, but does not run it
  • q — Quotes the substituted words, thus preventing further substitutions
  • x — Acts like the q modifier, but breaks into words at blanks, tabs, and newline characters

When using the preceding modifiers, the change applies only to the first modifiable word unless the g modifier precedes the selected modifier.

If you give a history reference without an event specification (for example, !$), the shell uses the previous command as the event. If a previous history reference occurs on the same line, the shell repeats the previous reference. Thus, the following sequence gives the first and last arguments of the command that matches ?foo?.

text
!?foo?^ !$

A special abbreviation of a history reference occurs when the first nonblank character of an input line is a carat (^). This is equivalent to !:s^, thus providing a convenient shorthand for substitutions on the text of the previous line. The command ^ lb^ lib corrects the spelling of lib in the command.

If necessary, you can enclose a history substitution in braces { } to insulate it from the characters that follow. For example, if you want to use a reference to the command:

text
ls -ld ~paul

to perform the command:

text
ls -ld ~paula

use the following construction:

text
!{l}a

In this example, !{l}a looks for a command starting with l and appends a to the end.

Quotation with single and double quotes:

To prevent further interpretation of all or some of the substitutions, enclose strings in single and double quotation marks.

Enclosing strings in ’ ’ prevents further interpretation, while enclosing strings in " " allows further expansion. In both cases, the text that results becomes all or part of a single word.

Input and output redirection in the C shell

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

You can redirect the standard input and output of a command with the following syntax statements:

  • < File — Opens the specified File (which is first variable, command, and file name expanded) as the standard input.
  • <<Word — Reads the shell input up to the line that matches the value of the Word variable. The Word variable is not subjected to variable, file name, or command substitution. Each input line is compared to the Word variable before any substitutions are done on the line. Unless a quoting character (\, ", ’ or ') appears in the Word variable, the shell performs variable and command substitution on the intervening lines, allowing the \ character to quote the $, \, and ' characters. Commands that are substituted have all blanks, tabs, and newline characters preserved, except for the final newline character, which is dropped. The resultant text is placed in an anonymous temporary file, which is given to the command as standard input.
  • > File >!File >& File >&! File — Uses the specified File as standard output. If File does not exist, it is created. If File exists, it is truncated, and its previous contents are lost. If the noclobber shell variable is set, File must not exist or be a character special file, or an error results. This helps prevent accidental destruction of files. In this case, use the forms including a ! to suppress this check. File is expanded in the same way as < input file names. The form >& redirects both standard output and standard error to the specified File. The following example shows how to separately redirect standard output to /dev/tty and standard error to /dev/null. The parentheses are required to allow standard output and standard error to be separate. % (find / -name vi -print > /dev/tty) >& /dev/null
  • > >File > >!File > >& File > >&! File — Uses the specified File as standard output like >, but appends output to the end of File. If the noclobber shell variable is set, an error results if File does not exist, unless one of the forms including a ! is given. Otherwise, it is similar to >.

A command receives the environment in which the shell was invoked, as changed by the input/output parameters and the presence of the command as a pipeline. Thus, unlike some previous shells, commands that run from a shell script do not have access to the text of the commands by default. Instead, they receive the original standard input of the shell. Use the << mechanism to present inline data, which allows shell command files to function as components of pipelines and also lets the shell block read its input. Note that the default standard input for a command run detached is not changed to the empty /dev/null file. Instead, the standard input remains the original standard input of the shell.

To redirect the standard error through a pipe with the standard output, use the form |& rather than only the |.

Flow control in the C shell:

The shell contains commands that can be used to regulate the flow of control in command files (shell scripts) and (in limited but useful ways) from shell command-line input. These commands all operate by forcing the shell to repeat, or skip, in its input.

The foreach, switch, and while statements, and the if-then-else form of the if statement, require that the major keywords appear in a single simple command on an input line.

If the shell input is not searchable, the shell buffers input whenever a loop is being read and searches the internal buffer to do the re-reading implied by the loop. To the extent that this is allowed, backward gotos succeed on inputs that you cannot search.