[AIX 운영 체제와 장치 관리 24] Bourne 셸 — 환경, 조건부 치환, 위치 매개변수, 파일 이름 치환, 방향 바꾸기, 내장 명령, 복합 명령, 명령·변수 치환, 셸 변수

핵심 정리

  • Bourne 셸은 login이 -bsh로 호출하면 로그인 셸이 되어 /etc/profile과 $HOME/.profile을 읽습니다. 키워드 매개변수는 호출하는 절차의 환경에만 들어가며 $#에 세지 않습니다.
  • 조건부 치환은 ${V-S}·${V=S}·${V?S}·${V+S}가 설정 여부만, 콜론이 붙은 형식이 설정·비어 있지 않음을 함께 봅니다.
  • 위치 매개변수는 $0~$9이고 그 위는 shift로 씁니다. 파일 이름 치환은 *, ?, [...], [!...]만 지원하며 동치 클래스는 없습니다.
  • 명령 검색 기본 순서는 /usr/bin, /etc, /usr/sbin, /usr/ucb, $HOME/bin, /usr/bin/X11, /sbin, 현재 디렉터리이며, 찾은 위치는 hash로 기억하고 PATH를 바꾸거나 hash -r이면 잊습니다.
  • 명령 치환은 역따옴표만 쓰며 중첩하려면 안쪽 역따옴표에 백슬래시를 붙입니다. MAILMSG, SHACCT, TIMEOUT(분) 같은 Bourne 셸 고유 변수가 있습니다.
항목 내용
버전 AIX 6.1 (5.3판과 거의 같음)
원문 Operating system and device management — 5.3판 441454쪽, 6.1판 248261쪽
관련 명령어 bsh, export, readonly, env, set, shift, hash, trap, type, ulimit, umask, wait
관련 파일 /etc/profile, $HOME/.profile, /etc/environment

Bourne 셸은 대화식 명령 해석기이자 명령 프로그래밍 언어입니다.

bsh 명령이 Bourne 셸을 실행합니다.

Bourne 셸은 로그인 셸로도, 로그인 셸 아래의 서브셸로도 실행할 수 있습니다. Bourne 셸을 로그인 셸로 호출할 수 있는 것은 login 명령뿐입니다. login은 bsh 명령 이름의 특수한 형태 -bsh를 써서 호출합니다. 앞에 하이픈(-)을 붙여 호출하면 셸은 먼저 시스템 /etc/profile 파일과 (있으면) $HOME/.profile의 명령을 읽어 실행합니다. /etc/profile 파일은 모든 사용자에게 필요한 변수를 설정합니다. 마지막으로 셸은 표준 입력에서 명령을 읽을 준비를 합니다.

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

관련 개념

  • 제공되는 셸

Bourne 셸 환경

명령이 실행을 시작할 때 아는 모든 변수(와 그 값)가 그 명령의 환경을 이룹니다. 이 환경에는 명령이 부모 프로세스에서 물려받은 변수와, 명령을 호출하는 명령행에서 키워드 매개변수로 지정한 변수가 들어 있습니다.

셸은 내장 export 명령의 인수로 지정한 변수를 자식 프로세스에 넘깁니다. 이 명령은 지정한 변수를 셸과 앞으로의 모든 자식 프로세스의 환경에 넣습니다.

키워드 매개변수는 보통 명령행에서 프로시저 이름 앞에 할당 꼴로 나오는 변수-값 쌍입니다(set 명령의 플래그도 봅니다). 이 변수들은 호출하는 프로시저의 환경에 들어갑니다.

다음 예를 봅니다.

  • 두 변수의 값을 보여 주는 다음 프로시저(key_command라는 명령 파일에 저장)를 생각해 봅니다.
text
# key_command
echo $a $b

다음 명령행은 표시한 출력을 냅니다.

text
Input                              Output
a=key1   b=key2  key_command       key1 key2
a=tom    b=john  key_command       tom john

프로시저의 키워드 매개변수는 $#에 저장되는 매개변수 수에 들어가지 않습니다.

프로시저는 환경에 있는 모든 변수의 값에 접근할 수 있습니다. 그러나 이 값을 바꿔도 셸 환경에는 반영되지 않습니다. 변경은 그 프로시저에 한정됩니다. 프로시저가 자식 프로세스에 넘기는 환경에 변경을 넣으려면 프로시저 안에서 새 값을 내보내야 합니다.

다음 예를 봅니다.

  • 현재 셸에서 내보낼 수 있는 변수 목록을 얻으려면 다음을 입력합니다.
text
export
  • 현재 셸의 읽기 전용 변수 목록을 얻으려면 다음을 입력합니다.
text
readonly
  • 현재 환경의 변수-값 쌍 목록을 얻으려면 다음을 입력합니다.
text
env

사용자 환경에 관한 자세한 내용은 /etc/environment 파일을 봅니다.

Bourne 셸의 조건부 치환

보통 셸은 $Variable 식을 Variable에 할당된 문자열 값(있으면)으로 바꿉니다. 그러나 변수가 설정됐는지, 비어 있지 않은지, 또는 둘 다에 따라 조건부로 치환하는 특수 표기가 있습니다.

정의상 변수에 한 번이라도 값을 할당했으면 변수가 설정된 것입니다. 변수 값은 빈 문자열일 수 있으며, 다음 방법 가운데 하나로 변수에 빈 문자열을 할당할 수 있습니다.

  • A=, bcd="", Efg='' — A, bcd, Efg에 빈 문자열을 할당합니다.
  • set '' "" — 첫째와 둘째 위치 매개변수를 빈 문자열로 설정하고 다른 위치 매개변수를 모두 해제합니다.

다음은 조건부 치환에 쓸 수 있는 식입니다.

  • ${Variable-String} — 변수가 설정돼 있으면 이 식 자리에 Variable 값을 넣습니다. 아니면 String 값으로 바꿉니다.
  • ${Variable:-String} — 변수가 설정돼 있고 비어 있지 않으면 Variable 값을 넣습니다. 아니면 String 값으로 바꿉니다.
  • ${Variable=String} — 변수가 설정돼 있으면 Variable 값을 넣습니다. 아니면 Variable을 String 값으로 설정한 뒤 Variable 값을 넣습니다. 위치 매개변수에는 이 방법으로 값을 할당할 수 없습니다.
  • ${Variable:=String} — 변수가 설정돼 있고 비어 있지 않으면 Variable 값을 넣습니다. 아니면 Variable을 String 값으로 설정한 뒤 Variable 값을 넣습니다. 위치 매개변수에는 이 방법으로 값을 할당할 수 없습니다.
  • ${Variable?String} — 변수가 설정돼 있으면 Variable 값을 넣습니다. 아니면 Variable: String 꼴의 메시지를 보여 주고 (로그인 셸이 아니면) 현재 셸을 끝냅니다. String 값을 지정하지 않으면 Variable: parameter null or not set 메시지를 보여 줍니다.
  • ${Variable:?String} — 변수가 설정돼 있고 비어 있지 않으면 Variable 값을 넣습니다. 아니면 Variable: String 꼴의 메시지를 보여 주고 (로그인 셸이 아니면) 현재 셸을 끝냅니다. String 값을 지정하지 않으면 Variable: parameter null or not set 메시지를 보여 줍니다.
  • ${Variable+String} — 변수가 설정돼 있으면 String 값을 넣습니다. 아니면 빈 문자열을 넣습니다.
  • ${Variable:+String} — 변수가 설정돼 있고 비어 있지 않으면 String 값을 넣습니다. 아니면 빈 문자열을 넣습니다.

조건부 치환에서 셸은 String을 치환 문자열로 쓸 때까지 평가하지 않습니다. 그래서 다음 예에서 셸은 d가 설정되지 않았거나 비어 있을 때만 pwd 명령을 실행합니다.

text
echo ${d:-`pwd`}

관련 개념

  • Bourne 셸의 사용자 정의 변수

Bourne 셸의 위치 매개변수

셸 프로시저를 실행하면 셸은 명령행의 각 단어를 위치로 가리키는 위치 매개변수를 암묵적으로 만듭니다.

위치 0의 단어(프로시저 이름)는 $0, 다음 단어(첫 매개변수)는 $1, 이런 식으로 $9까지 부릅니다. 9보다 큰 번호의 명령행 매개변수를 가리키려면 내장 shift 명령을 씁니다.

내장 set 명령으로 위치 매개변수 값을 명시적으로 다시 설정할 수 있습니다.

참고: 어떤 위치의 인수를 지정하지 않으면 그 위치 매개변수는 빈 값으로 설정됩니다. 위치 매개변수는 전역이며 중첩한 셸 프로시저에 넘길 수 있습니다.

관련 개념

  • Bourne 셸의 사용자 정의 변수

관련 참조

  • Bourne 셸의 미리 정의된 특수 변수

Bourne 셸의 파일 이름 치환

Bourne 셸에서는 파일 이름 치환을 할 수 있습니다.

명령 매개변수는 파일 이름인 경우가 많습니다. 명령행에 매개변수로 파일 이름 목록을 자동으로 만들 수 있습니다. 그러려면 셸이 패턴 일치 문자로 인식하는 문자를 지정합니다. 명령에 그런 문자가 있으면 셸은 그것을 디렉터리의 파일 이름들로 바꿉니다.

참고: Bourne 셸은 문자의 동치 분류에 기반한 파일 이름 펼치기를 지원하지 않습니다.

이런 패턴에서 대부분의 문자는 자기 자신과 맞지만, 특수 패턴 일치 문자도 쓸 수 있습니다. 특수 문자는 다음과 같습니다.

  • * — 빈 문자열을 포함해 어떤 문자열과도 일치합니다.
  • ? — 아무 한 문자와 일치합니다.
  • [...] — 대괄호 안 문자 가운데 하나와 일치합니다.
  • [!...] — 대괄호 안에서 느낌표 뒤의 문자를 뺀 아무 문자와 일치합니다.

대괄호 안에서 하이픈(-)으로 구분한 문자 쌍은 문자 값의 이진 순서에 따라 그 쌍 사이(양끝 포함)에 있는 모든 문자의 집합을 뜻합니다.

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

text
.*file

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

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

Bourne 셸의 입출력 방향 바꾸기

명령에 쓸 수 있는 방향 바꾸기 옵션이 있습니다.

일반적으로 대부분의 명령은 입력이나 출력이 키보드, 화면, 파일 가운데 어디와 연결돼 있는지 모릅니다. 그래서 명령을 키보드에서나 파이프라인에서나 편하게 쓸 수 있습니다.

다음 방향 바꾸기 옵션은 단순 명령 안 어디에나 나올 수 있습니다. 명령 앞이나 뒤에 올 수도 있지만 명령에 넘어가지는 않습니다.

  • <File — 지정한 파일을 표준 입력으로 씁니다.
  • >File — 지정한 파일을 표준 출력으로 씁니다. 파일이 없으면 만들고, 있으면 길이를 0으로 자릅니다.
  • >>File — 지정한 파일을 표준 출력으로 씁니다. 파일이 없으면 만들고, 있으면 출력을 파일 끝에 덧붙입니다.
  • <<[-]eofstr — eofstr만 있는 줄이나 파일 끝 문자까지의 모든 줄을 표준 입력으로 읽습니다. eofstr의 문자가 하나라도 따옴표로 감싸져 있으면 셸은 입력 줄의 문자를 펼치거나 해석하지 않습니다. 아니면 변수와 명령 치환을 하고 따옴표로 감싼 줄 바꿈 문자(백슬래시+줄 바꿈)는 무시합니다. eofstr 안이나 입력 줄 안의 문자를 따옴표 처리하려면 백슬래시(\)를 씁니다. << 방향 바꾸기 옵션에 하이픈(-)을 붙이면 eofstr과 입력 줄의 앞쪽 탭을 모두 지웁니다.
  • <&Digit — Digit로 지정한 파일 기술자를 표준 입력과 연결합니다.
  • >&Digit — Digit로 지정한 파일 기술자를 표준 출력과 연결합니다.
  • <&- — 표준 입력을 닫습니다.
  • >&- — 표준 출력을 닫습니다.

참고: 제한 셸은 출력 방향 바꾸기를 허용하지 않습니다.

방향 바꾸기에 관한 자세한 내용은 입출력 방향 바꾸기를 봅니다.

Bourne 셸 내장 명령 목록

다음은 Bourne 셸 내장 명령 목록입니다.

명령 설명
: 종료 값 0을 돌려줍니다.
. file 매개변수의 명령을 읽어 실행하고 돌아옵니다.
break 둘러싼 for, while, until 반복이 있으면 빠져나갑니다.
cd 현재 디렉터리를 지정한 디렉터리로 바꿉니다.
continue 둘러싼 for, while, until 반복의 다음 반복으로 넘어갑니다.
echo 문자열을 표준 출력에 씁니다.
eval 인수를 셸 입력으로 읽고 결과 명령을 실행합니다.
exec 새 프로세스를 만들지 않고 이 셸 대신 Argument 매개변수로 지정한 명령을 실행합니다.
exit n 매개변수로 지정한 종료 상태로 셸을 끝냅니다.
export 이후 실행하는 명령의 환경으로 자동으로 내보낼 이름을 표시합니다.
hash 지정한 명령의 검색 경로상 위치를 찾아 기억합니다.
pwd 현재 디렉터리를 보여 줍니다.
read 표준 입력에서 한 줄을 읽습니다.
readonly Name 매개변수로 지정한 이름을 읽기 전용으로 표시합니다.
return 지정한 반환 값으로 함수를 끝냅니다.
set 여러 매개변수를 표준 출력에 보여 주는 것을 제어합니다.
shift 명령행 인수를 왼쪽으로 옮깁니다.
test 조건식을 평가합니다.
times 셸에서 실행한 프로세스의 누적 사용자·시스템 시간을 보여 줍니다.
trap 셸이 지정한 신호를 받으면 지정한 명령을 실행합니다.
type 지정한 이름을 셸이 명령 이름으로 어떻게 해석할지 알려 줍니다.
ulimit 할당된 셸 자원을 보여 주거나 조정합니다.
umask 파일 권한을 정합니다.
unset 지정한 이름에 해당하는 변수나 함수를 지웁니다.
wait 지정한 자식 프로세스가 끝나기를 기다렸다가 종료 상태를 알립니다.

관련 참조

  • Bourne 셸 내장 명령

Bourne 셸 명령

Bourne 셸에서 명령을 내릴 수 있습니다.

Bourne 셸에서 명령을 내리면 셸은 먼저 명령을 평가하고 지정한 모든 치환을 합니다. 그런 다음 다음 조건이면 명령을 실행합니다.

  • 명령 이름이 Bourne 셸 특수 내장 명령입니다. 또는
  • 명령 이름이 정의된 함수 이름과 맞습니다. 이 경우 셸은 위치 매개변수를 함수의 매개변수로 설정합니다.

명령 이름이 내장 명령이나 정의된 함수 이름과 맞지 않고 명령이 컴파일된(바이너리) 프로그램인 실행 파일을 가리키면, 셸(부모)은 새 (자식) 프로세스를 만들어 바로 프로그램을 실행합니다. 파일이 실행 가능하게 표시돼 있지만 컴파일된 프로그램이 아니면 셸은 셸 프로시저라고 봅니다. 이때 셸은 자신의 또 다른 인스턴스(서브셸)를 만들어 파일을 읽고 그 안의 명령을 실행합니다. 괄호로 감싼 명령도 서브셸에서 실행합니다. 사용자 입장에서 컴파일된 프로그램은 셸 프로시저와 똑같은 방식으로 실행됩니다. 셸은 보통 다음 순서로 파일 시스템 디렉터리에서 명령을 찾습니다.

  1. /usr/bin
  2. /etc
  3. /usr/sbin
  4. /usr/ucb
  5. $HOME/bin
  6. /usr/bin/X11
  7. /sbin
  8. 현재 디렉터리

셸은 각 디렉터리를 차례로 찾으며 명령을 찾지 못하면 다음 디렉터리로 넘어갑니다.

참고: PATH 변수가 셸이 디렉터리를 찾는 순서를 정합니다. PATH 변수를 다시 설정해 찾는 디렉터리 순서를 바꿀 수 있습니다.

명령을 실행할 때 특정 경로 이름(예: /usr/bin/sort)을 주면 셸은 지정한 디렉터리 외의 디렉터리는 찾지 않습니다. 명령 이름에 슬래시(/)가 있으면 셸은 검색 경로를 쓰지 않습니다.

루트 디렉터리로 시작하는 전체 경로 이름(예: /usr/bin/sort)을 줄 수 있습니다. 현재 디렉터리에 대한 상대 경로 이름도 지정할 수 있습니다. 예를 들어 다음을 지정하면

text
bin/myfile

셸은 현재 디렉터리에서 bin이라는 디렉터리를 찾고 그 디렉터리에서 myfile 파일을 찾습니다.

참고: 제한 셸은 슬래시(/)가 든 명령을 실행하지 않습니다.

셸은 (나중에 불필요한 exec 명령을 피하려고) 실행한 각 명령의 검색 경로상 위치를 기억합니다. 상대 디렉터리(이름이 /로 시작하지 않는 디렉터리)에서 명령을 찾았으면 현재 디렉터리가 바뀔 때마다 명령 위치를 다시 정해야 합니다. PATH 변수를 바꾸거나 hash -r 명령을 실행할 때마다 셸은 기억한 위치를 모두 잊습니다.

문자 따옴표

많은 문자가 셸에 특별한 뜻을 가집니다. 그 뜻을 숨기고 싶을 때가 있습니다. 문자열을 작은따옴표(')나 큰따옴표(")로 감싸거나 문자 하나 앞에 백슬래시(\)를 붙이면 문자의 뜻을 숨길 수 있습니다.

(감싸는 작은따옴표를 뺀) 모든 문자는 특별한 뜻이 없어지고 글자 그대로 취급됩니다. 그래서 다음 명령은

text
stuff=’echo $? $*; ls * | wc’

글자 그대로의 문자열 echo $? $*; ls * | wc를 변수 stuff에 할당합니다. 셸은 echo, ls, wc 명령을 실행하지 않고, $?와 $* 변수와 별표(*) 특수 문자도 펼치지 않습니다.

큰따옴표 안에서는 달러 기호($), 역따옴표, 큰따옴표(") 문자의 특별한 뜻이 유지되고 다른 모든 문자는 글자 그대로 취급됩니다. 그래서 큰따옴표 안에서는 명령과 변수 치환이 일어납니다. 또 따옴표는 따옴표 문자열의 일부인 명령 치환 안의 명령에는 영향을 주지 않으므로, 거기 있는 문자는 특별한 뜻을 유지합니다.

다음 순서를 봅니다.

text
ls *
file1 file2 file3
message="This directory contains `ls * ` "
echo $message
This directory contains file1 file2 file3

명령 치환 안의 별표(*) 특수 문자가 펼쳐졌음을 보여 줍니다.

큰따옴표 안에서 달러 기호($), 역따옴표, 큰따옴표(") 문자의 특별한 뜻을 숨기려면 앞에 백슬래시(\)를 붙입니다. 큰따옴표를 쓰지 않을 때 문자 앞에 백슬래시를 붙이는 것은 작은따옴표로 감싸는 것과 같습니다. 그래서 줄 바꿈 문자 바로 앞의 백슬래시(곧 줄 끝의 백슬래시)는 줄 바꿈 문자를 숨겨 다음 물리적 줄에서 명령행을 이어 쓸 수 있게 합니다.

신호 처리

호출한 명령이 앰퍼샌드(&)로 끝나면, 곧 백그라운드에서 실행 중이면 셸은 그 명령의 INTERRUPT와 QUIT 신호를 무시합니다. 그렇지 않으면 신호는 SEGMENTATION VIOLATION 신호를 빼고 셸이 부모에게서 물려받은 값을 가집니다.

자세한 내용은 Bourne 셸 내장 trap 명령을 봅니다.

Bourne 셸 복합 명령

복합 명령은 다음 가운데 하나입니다.

  • 파이프라인(파이프(|) 기호로 구분한 단순 명령 하나 이상)
  • 단순 명령 목록
  • 예약어로 시작하는 명령
  • 제어 연산자 여는 괄호(()로 시작하는 명령

따로 적지 않으면 복합 명령이 돌려주는 값은 마지막으로 실행한 단순 명령의 값입니다.

예약어

Bourne 셸의 다음 예약어는 따옴표 없이 명령의 첫 단어로 나올 때만 인식됩니다.

for, do, done, case, esac, if, then, fi, elif, else, while, until, {, }, (, )

  • for Identifier [in Word ...] do List done — Identifier를 Word로 지정한 단어로 (하나씩) 설정하고 List의 명령을 실행합니다. in Word ...를 생략하면 설정된 위치 매개변수마다 List를 실행하고, 위치 매개변수를 모두 쓰면 처리가 끝납니다.
  • case Word in Pattern [| Pattern] ...) List;; [Pattern [| Pattern] ...) List;;] ... esac — Word 값과 맞는 첫 Pattern에 연결된 List의 명령을 실행합니다. 패턴에는 파일 이름 치환과 같은 문자 일치 표기를 쓰지만, 슬래시(/), 앞쪽 점(.), 슬래시 바로 뒤의 점(/.)을 명시적으로 맞출 필요는 없습니다.
  • if List then List [elif List then List] ... [else List] fi — if 명령 뒤의 List 명령을 실행합니다. 명령이 종료 값 0을 돌려주면 첫 then 명령 뒤의 List를 실행합니다. 아니면 elif 명령(있으면) 뒤의 List를 실행합니다. 이 종료 값이 0이면 다음 then 명령 뒤의 List를 실행합니다. 명령이 0이 아닌 종료 값을 돌려주면 else 명령(있으면) 뒤의 List를 실행합니다. else List나 then List를 실행하지 않으면 if 명령은 종료 값 0을 돌려줍니다.
  • while List do List done — while 명령 뒤의 List 명령을 실행합니다. while List의 마지막 명령 종료 값이 0이면 do 명령 뒤의 List를 실행합니다. while List의 마지막 명령 종료 값이 0이 아닐 때까지 목록을 반복합니다. do List의 명령을 하나도 실행하지 않으면 while 명령은 종료 값 0을 돌려줍니다.
  • until List do List done — until 명령 뒤의 List 명령을 실행합니다. until List의 마지막 명령 종료 값이 0이 아니면 do 뒤의 List를 실행합니다. until List의 마지막 명령 종료 값이 0일 때까지 목록을 반복합니다. do List의 명령을 하나도 실행하지 않으면 until 명령은 종료 값 0을 돌려줍니다.
  • ( List ) — List의 명령을 서브셸에서 실행합니다.
  • { List; } — List의 명령을 현재 셸 프로세스에서 실행하며 서브셸을 시작하지 않습니다.
  • Name () { List } — Name으로 가리키는 함수를 정의합니다. 함수 본문은 List로 지정한 중괄호 사이의 명령 목록입니다.

Bourne 셸 내장 명령

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

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

다음 특수 명령은 다른 특수 내장 명령과 조금 다르게 취급됩니다.

continue, readonly, wait, eval, return (6.1판 표가 깨져 이렇게만 남음)

Bourne 셸은 이 명령들을 다음과 같이 처리합니다.

  • 명령 앞의 키워드 매개변수 할당 목록이 명령이 끝난 뒤에도 유효합니다.
  • 입출력 방향 바꾸기는 매개변수 할당 뒤에 처리합니다.
  • 셸 스크립트의 오류는 스크립트 처리를 멈춥니다.

관련 참조

  • Bourne 셸 내장 명령 목록

특수 명령 설명

Bourne 셸은 다음 특수 내장 명령을 제공합니다.

  • : — 종료 값 0을 돌려줍니다.

  • . File — File 매개변수의 명령을 읽어 실행하고 돌아옵니다. 서브셸을 시작하지 않습니다. 셸은 PATH 변수의 검색 경로로 지정한 파일이 든 디렉터리를 찾습니다.

  • break [n] — 둘러싼 for, while, until 반복이 있으면 빠져나갑니다. n을 지정하면 n단계를 빠져나갑니다.

  • continue [n] — 둘러싼 for, while, until 반복의 다음 반복으로 넘어갑니다. n을 지정하면 n번째 둘러싼 반복에서 이어갑니다.

  • cd [Directory] — 현재 디렉터리를 Directory로 바꿉니다. Directory를 지정하지 않으면 HOME 셸 변수 값을 씁니다. CDPATH 셸 변수가 Directory의 검색 경로를 정합니다. CDPATH는 다른 디렉터리 이름을 콜론으로 구분한 목록입니다. 빈 경로 이름은 현재 디렉터리(기본 경로)를 뜻합니다. 이 빈 경로 이름은 할당의 등호 바로 뒤나 경로 목록 다른 곳의 콜론 구분자 사이에 나옵니다. Directory가 슬래시(/)로 시작하면 검색 경로를 쓰지 않습니다. 아니면 CDPATH 셸 변수의 각 디렉터리를 찾습니다. 참고: 제한 셸은 cd 셸 명령을 실행할 수 없습니다.

  • echo [String ...] — 문자열을 표준 출력에 씁니다. 사용법과 매개변수는 echo 명령을 봅니다. -n 플래그는 지원하지 않습니다.

  • eval [Argument ...] — 인수를 셸 입력으로 읽고 결과 명령을 실행합니다.

  • exec [Argument ...] — 새 프로세스를 만들지 않고 이 셸 대신 Argument로 지정한 명령을 실행합니다. 입출력 인수가 나올 수 있으며, 다른 인수가 없으면 셸 입력이나 출력을 바꿉니다. 로그인 셸에서는 권하지 않습니다.

  • exit [n] — n으로 지정한 종료 값으로 셸을 끝냅니다. 생략하면 마지막으로 실행한 명령의 종료 값입니다(Ctrl-D 키로도 셸이 끝납니다). n 값은 0부터 255까지입니다.

  • export [Name ...] — 지정한 이름을 이후 실행하는 명령의 환경으로 자동으로 내보내도록 표시합니다. Name을 지정하지 않으면 이 셸에서 내보낸 모든 이름 목록을 보여 줍니다. 함수 이름은 내보낼 수 없습니다.

  • hash [-r] [Command ...] — 지정한 각 Command의 검색 경로상 위치를 찾아 기억합니다. -r 플래그는 기억한 위치를 모두 잊게 합니다. 플래그도 명령도 지정하지 않으면 기억한 명령 정보를 Hits Cost Command 형식으로 보여 줍니다. Hits는 셸 프로세스가 명령을 실행한 횟수, Cost는 검색 경로에서 명령을 찾는 데 든 작업량, Command는 지정한 각 명령의 경로 이름입니다. 현재 디렉터리가 바뀔 때 상대 경로 이름의 위치처럼 저장한 위치를 다시 계산해야 하는 경우가 있습니다. 그럴 수 있는 명령은 Hits 정보 옆에 별표(*)로 표시합니다. 다시 계산하면 Cost가 늘어납니다.

  • pwd — 현재 디렉터리를 보여 줍니다. 명령 옵션은 pwd 명령을 봅니다.

  • read [Name ...] — 표준 입력에서 한 줄을 읽습니다. 줄의 첫 단어를 첫 Name에, 둘째 단어를 둘째 Name에 할당하는 식으로 하고, 남는 단어는 마지막 Name에 할당합니다. 파일 끝 문자를 만나지 않으면 0을 돌려줍니다.

  • readonly [Name ...] — Name으로 지정한 이름을 읽기 전용으로 표시합니다. 그 값은 다시 설정할 수 없습니다. Name을 지정하지 않으면 모든 읽기 전용 이름 목록을 보여 줍니다.

  • return [n] — 반환 값 n으로 함수를 끝냅니다. n을 지정하지 않으면 함수에서 마지막으로 실행한 명령의 상태를 돌려줍니다. 셸 함수 안에서 실행할 때만 유효합니다.

  • set [Flag [Argument] ...] — 다음 플래그 가운데 하나 이상을 설정합니다.

    • -a — 할당하는 모든 변수를 내보내기로 표시합니다. 할당이 명령 이름 앞에 오면 내보내기 속성은 특수 내장 명령 앞인 경우를 빼고 그 명령 실행 환경에서만 유효합니다. 특수 내장 명령 앞이면 내장 명령이 끝난 뒤에도 남습니다. 할당이 명령 이름 앞에 오지 않거나 getopts·read 명령의 동작 결과이면 변수를 해제할 때까지 내보내기 속성이 남습니다.
    • -e — 명령이 다음 조건을 모두 만족하면 바로 끝냅니다. 0보다 큰 반환 값으로 끝남, while·until·if 명령의 복합 목록의 일부가 아님, AND나 OR 목록으로 시험하는 중이 아님, !(느낌표) 예약어가 앞에 붙은 파이프라인이 아님.
    • -f — 파일 이름 치환을 끕니다.
    • -h — 함수를 정의할 때 함수 안에서 호출하는 명령을 찾아 기억합니다(보통은 함수를 실행할 때 찾습니다. hash 명령을 봅니다).
    • -k — 명령 이름 앞의 것뿐 아니라 모든 키워드 매개변수를 명령의 환경에 넣습니다.
    • -n — 명령을 읽지만 실행하지 않습니다. 셸 스크립트의 구문 오류를 확인하려면 -n 플래그를 씁니다.
    • -t — 명령 하나를 읽고 실행한 뒤 끝냅니다.
    • -u — 변수 치환을 할 때 설정되지 않은 변수를 오류로 취급하고 바로 끝냅니다. 대화식 셸은 끝나지 않습니다.
    • -v — 셸 입력 줄을 읽는 대로 보여 줍니다.
    • -x — 명령과 인수를 실행하기 전에 보여 줍니다.
    • -- — 어떤 플래그도 바꾸지 않습니다. $1 위치 매개변수를 하이픈(-)으로 시작하는 문자열로 설정할 때 쓸모 있습니다.

    하이픈(-) 대신 더하기 기호(+)를 쓰면 플래그를 해제합니다. 셸 명령행에서도 이 플래그를 지정할 수 있습니다. $- 특수 변수에 현재 플래그가 들어 있습니다. set 명령의 Argument는 위치 매개변수가 되어 차례로 $1, $2, ...에 할당됩니다. 플래그도 Argument도 지정하지 않으면 현재 셸 변수의 이름과 값을 모두 보여 줍니다.

  • shift [n] — 명령행 인수를 왼쪽으로 옮깁니다. 곧 $1의 현재 값을 버리고 $2의 값을 $1에, $3의 값을 $2에 할당하는 식으로 위치 매개변수 값을 다시 할당합니다. 명령행 인수가 9개보다 많으면 10번째가 $9에 할당되고 나머지는 (다음 shift까지) 할당되지 않은 채 남습니다. 인수가 9개 이하이면 shift 명령은 값이 있는 가장 큰 번호의 위치 매개변수를 해제합니다. $0 위치 매개변수는 옮기지 않습니다. shift n은 n번 연속 shift의 줄임 표기입니다. n의 기본값은 1입니다.

  • test Expression, [ Expression ] — 조건식을 평가합니다. 명령 플래그와 매개변수는 test 명령을 봅니다. bsh의 내장 test 명령은 -h 플래그를 지원하지 않습니다.

  • times — 셸에서 실행한 프로세스의 누적 사용자·시스템 시간을 보여 줍니다.

  • trap [Command] [n] ... — n으로 지정한 신호를 셸이 받으면 Command로 지정한 명령을 실행합니다. trap 명령은 신호 번호 순서로 실행됩니다. 현재 셸에 들어올 때 무시된 신호에 trap을 설정하려는 시도는 효과가 없습니다. 참고: 셸은 trap을 설정할 때 한 번, trap이 걸릴 때 다시 Command를 훑습니다. 명령을 지정하지 않으면 n으로 지정한 모든 trap을 현재 값(원문 그대로, 원래 값)으로 되돌립니다. 빈 문자열을 지정하면 셸과 셸이 호출하는 명령이 이 신호를 무시합니다. n이 0이면 셸을 끝낼 때 지정한 명령을 실행합니다. 명령도 신호도 지정하지 않으면 신호 번호마다 연결된 명령 목록을 보여 줍니다.

  • type [Name ...] — 지정한 각 Name을 명령 이름으로 쓰면 셸이 어떻게 해석할지 알려 줍니다.

  • ulimit [-HS] [-c | -d | -f | -m | -r | -s | -t | -u] [limit] — 할당된 셸 자원을 보여 주거나 조정합니다. 셸 자원 설정은 하나씩 또는 묶음으로 보여 줄 수 있습니다. 기본 모드는 소프트 설정(하한)으로 설정한 자원을 묶음으로 보여 주는 것입니다.

    셸 자원 설정은 현재 셸의 유효 사용자 ID에 따라 다릅니다. 자원의 하드 수준은 현재 셸의 유효 사용자 ID가 root일 때만 설정할 수 있습니다. root가 아닌데 하드 수준을 설정하려 하면 오류가 납니다. 기본적으로 root 사용자는 자원의 하드와 소프트 한도를 모두 설정합니다. 그래서 root 사용자는 -S, -H, 또는 기본 플래그 사용에 주의해야 합니다. root가 아니면 소프트 한도만 설정할 수 있습니다. root가 아닌 사용자가 한도를 낮추면 원래 시스템 한도로도 다시 올릴 수 없습니다.

    자원 한도를 설정하려면 알맞은 플래그와 새 자원의 한도 값(정수)을 고릅니다. 한 번에 자원 한도 하나만 설정할 수 있습니다. 자원 플래그를 여러 개 지정하면 결과가 정의되지 않습니다. 기본적으로 명령행에 새 값만 준 ulimit는 셸의 파일 크기를 설정합니다. -f 플래그는 선택입니다.

    ulimit 명령 플래그는 다음과 같습니다.

    • -c — 셸의 코어 세그먼트를 설정하거나 보여 줍니다.
    • -d — 셸의 데이터 세그먼트를 설정하거나 보여 줍니다.
    • -f — 셸의 파일 크기를 설정하거나 보여 줍니다.
    • -H — 하드 자원 한도를 설정하거나 보여 줍니다(root 사용자만).
    • -m — 셸의 메모리를 설정하거나 보여 줍니다.
    • -r — 프로세스당 최대 스레드 수를 설정하거나 보여 줍니다.
    • -s — 셸의 스택 세그먼트를 설정하거나 보여 줍니다.
    • -S — 소프트 자원 한도를 설정하거나 보여 줍니다.
    • -t — 셸의 최대 CPU 시간을 설정하거나 보여 줍니다.
    • -u — 사용자당 최대 프로세스 수를 설정하거나 보여 줍니다.
  • umask [nnn] — 파일 권한을 정합니다. 이 값은 만드는 프로세스의 권한과 함께 파일을 만들 때 파일 권한을 정합니다. 기본값은 022입니다. 값을 입력하지 않으면 현재 값을 보여 줍니다.

  • unset [Name ...] — Name으로 지정한 각 이름에 해당하는 변수나 함수를 지웁니다. PATH, PS1, PS2, MAILCHECK, IFS 셸 변수는 해제할 수 없습니다.

  • wait [n] — 프로세스 번호가 n인 자식 프로세스가 끝나기를 기다렸다가 그 프로세스의 종료 상태를 돌려줍니다. n을 지정하지 않으면 현재 활성인 모든 자식 프로세스를 기다리며 반환 값은 0입니다.

Bourne 셸의 명령 치환

명령 치환으로 어떤 명령의 출력이든 다른 명령의 인수로 잡을 수 있습니다.

명령행을 역따옴표로 감싸면 셸은 먼저 그 명령을 실행하고, 역따옴표를 포함한 식 전체를 출력으로 바꿉니다. 이 기능은 셸 변수에 값을 줄 때 자주 씁니다. 예를 들어 다음 문장은

text
today=`date`

현재 날짜를 나타내는 문자열을 today 변수에 할당합니다. 다음 할당은 현재 디렉터리의 파일 수를 files 변수에 저장합니다.

text
files=`ls | wc -l`

표준 출력에 쓰는 명령이면 무엇이든 명령 치환을 할 수 있습니다.

명령 치환을 중첩하려면 다음처럼 중첩한 각 역따옴표 앞에 백슬래시(\)를 붙입니다.

text
logmsg=`echo Your login directory is \`pwd\``

read 특수 명령으로 셸 변수에 간접적으로 값을 줄 수도 있습니다. 이 명령은 표준 입력(보통 키보드)에서 한 줄을 받아 그 줄의 연속된 단어를 지정한 변수에 할당합니다. 예를 들어 다음 명령은

text
read first init last

다음 꼴의 입력 줄을 받으면

text
J. Q. Public

다음을 입력한 것과 같은 효과를 냅니다.

text
first=J. init=Q. last=Public

read 특수 명령은 남는 단어를 마지막 변수에 할당합니다.

Bourne 셸의 변수 치환

Bourne 셸에서는 변수 치환을 할 수 있습니다.

Bourne 셸에는 변수를 만드는(이름에 문자열 값을 할당하는) 메커니즘이 여럿 있습니다. 어떤 변수, 위치 매개변수, 키워드 매개변수는 보통 명령행에서만 설정합니다. 다른 변수는 사용자나 셸이 문자열 값을 할당할 수 있는 이름일 뿐입니다.

관련 개념

  • 지켜보지 않는 터미널

Bourne 셸의 사용자 정의 변수

Bourne 셸은 문자열 값을 할당할 수 있는 영숫자 변수를 인식합니다.

이름에 문자열 값을 할당하려면 다음을 입력합니다.

text
Name=String

이름은 밑줄이나 문자로 시작하는 문자, 숫자, 밑줄의 연속입니다. 변수에 할당한 값을 쓰려면 이름 앞에 달러 기호($)를 붙입니다. 그래서 $Name은 String으로 지정한 값이 됩니다. 할당문에서 등호(=) 양쪽에 공백이 없다는 점에 주의합니다. 위치 매개변수는 할당문에 나올 수 없습니다. 명령행 하나에 할당을 여럿 넣을 수 있지만 셸은 할당을 오른쪽에서 왼쪽으로 한다는 점을 기억합니다.

String을 큰따옴표나 작은따옴표로 감싸면 셸은 문자열 안의 공백, 탭, 세미콜론, 줄 바꿈 문자를 단어 구분자로 취급하지 않고 문자열에 그대로 넣습니다.

String을 큰따옴표로 감싸면 셸은 여전히 문자열 안의 변수 이름을 인식해 변수 치환을 합니다. 곧 달러 기호($)가 앞에 붙은 위치 매개변수와 다른 변수 이름 참조를 해당 값(있으면)으로 바꿉니다. 큰따옴표로 감싼 문자열 안에서는 명령 치환도 합니다.

String을 작은따옴표로 감싸면 셸은 문자열 안의 변수나 명령을 치환하지 않습니다. 다음 순서가 그 차이를 보여 줍니다.

text
You:            num=875
                number1="Add $num"
                number2=’Add $num’
                echo $number1
System:         Add 875
You:            echo $number2
System:         Add $num

셸은 변수 치환을 한 뒤 할당의 공백을 다시 해석하지 않습니다. 그래서 다음 할당의 결과 $first와 $second는 같은 값을 가집니다.

text
first=’a string with embedded blanks’
second=$first

변수를 참조할 때 뒤따르는 문자열과 변수 이름을 구분하려고 변수 이름(이나 위치 매개변수를 나타내는 숫자)을 중괄호 { }로 감쌀 수 있습니다. 특히 이름 바로 뒤의 문자가 문자, 숫자, 밑줄이고 변수가 위치 매개변수가 아니면 중괄호가 필요합니다.

text
You:            a=’This is a’
                echo "${a}n example"
System:         This is an example
You:            echo "$a test"
System:         This is a test

관련 개념

  • Bourne 셸의 위치 매개변수

관련 참조

  • Bourne 셸의 조건부 치환

Bourne 셸이 쓰는 변수

셸은 다음 변수를 씁니다. 셸이 그 가운데 일부를 설정하지만 모두 설정하거나 다시 설정할 수 있습니다.

변수 설명
CDPATH cd(디렉터리 변경) 명령의 검색 경로
HOME 로그인 디렉터리 이름으로, 로그인이 끝나면 현재 디렉터리가 됩니다. login 프로그램이 초기화합니다. cd 명령은 $HOME 값을 기본값으로 씁니다. 셸 프로시저에서 명시적 경로 대신 쓰면 고치지 않고 다른 디렉터리에서 실행할 수 있습니다.
IFS 셸이 공백 해석에 쓰는 내부 필드 구분자 문자. 처음에는 스페이스, 탭, 줄 바꿈 문자로 설정됩니다.
LANG LC_ALL 변수와 해당 환경 변수(LC_로 시작)가 로케일을 지정하지 않을 때 로케일 범주에 쓸 로케일
LC_ALL LANG 환경 변수나 LC_로 시작하는 환경 변수가 지정한 로케일 범주 값을 모두 무시하고 쓸 로케일
LC_COLLATE 이름을 정렬할 때와 패턴에 문자 범위가 나올 때 쓸 정렬 순서
LC_CTYPE 텍스트 데이터의 바이트 열을 문자로 해석하는 로케일(인수와 입력 파일의 단일·멀티바이트 문자), 어떤 문자를 문자(alpha 클래스)로 정의하는지, 패턴 일치 안 문자 클래스의 동작
LC_MESSAGES 메시지를 쓸 언어
LIBPATH 공유 라이브러리 검색 경로
LOGNAME 로그인 이름. /etc/profile 파일에서 readonly로 표시됩니다.
MAIL 메일 시스템이 새 메일 도착을 감지하는 파일의 경로 이름. 설정돼 있으면 셸은 주기적으로 이 파일의 수정 시각을 확인해, 시각이 바뀌고 파일 길이가 0보다 크면 $MAILMSG 값을 보여 줍니다. .profile 파일에서 설정합니다. mail 명령 사용자가 보통 할당하는 값은 /usr/spool/mail/$LOGNAME입니다.
MAILCHECK MAILPATH나 MAIL 변수로 지정한 파일에 메일이 왔는지 다시 확인하기 전에 기다리는 초 수. 기본값은 600초(10분)입니다. 0으로 설정하면 프롬프트마다 확인합니다.
MAILMSG 메일 알림 메시지. 명시적으로 빈 문자열(MAILMSG="")로 설정하면 메시지를 보여 주지 않습니다.
MAILPATH 콜론으로 구분한 파일 이름 목록. 설정돼 있으면 목록의 파일에 메일이 오면 알립니다. 각 파일 이름 뒤에 %와 메일이 올 때 보여 줄 메시지를 붙일 수 있습니다. 붙이지 않으면 MAILMSG 값이나 기본 메시지 [YOU HAVE NEW MAIL]을 씁니다. 참고: MAILPATH를 설정하면 MAIL 변수의 파일 대신 이 파일들을 확인합니다. 둘 다 확인하려면 MAILPATH 목록에 MAIL 파일을 넣습니다.
PATH 명령 검색 경로. 콜론으로 구분한 디렉터리 경로 이름의 순서 목록이며 셸은 이 순서대로 명령을 찾습니다. 목록 어디든 빈 문자열은 현재 디렉터리를 뜻합니다. 보통 /etc/environment 파일에서 /usr/bin:/etc:/usr/sbin:/usr/ucb:/usr/bin/X11:/sbin으로 초기화합니다. .profile의 PATH에는 $HOME/bin과 현재 디렉터리도 들어 있습니다. 표준 시스템 디렉터리보다 먼저 찾을 프로젝트 디렉터리(예: /project/bin)가 있으면 PATH=/project/bin:$PATH로 설정합니다. 기본값이 아닌 값은 $HOME/.profile 파일에서 설정하는 것이 가장 좋습니다. 제한 셸에서는 PATH를 다시 설정할 수 없습니다.
PS1 1차 시스템 프롬프트 문자열. 대화식 셸은 입력을 기다릴 때 이 문자열을 보여 줍니다. 일반 사용자의 기본값은 $ 뒤에 스페이스입니다.
PS2 2차 프롬프트 문자열. 입력에서 줄 바꿈 문자를 만났는데 입력이 더 필요하면 이 값으로 프롬프트를 냅니다. 기본값은 > 뒤에 스페이스입니다.
SHACCT 자기가 소유한 파일 이름. 설정돼 있으면 셸은 실행한 셸 스크립트마다 이 파일에 계정 레코드를 씁니다. acctcom과 acctcms 같은 계정 프로그램으로 모은 데이터를 분석할 수 있습니다.
SHELL 셸의 경로 이름으로 환경에 유지됩니다. 제한 로그인마다 $HOME/.profile 파일에서 설정하고 내보내야 합니다.
TIMEOUT 셸이 끝나기 전에 입력 없이 기다리는 분 수. 0보다 크면 PS1 프롬프트를 낸 뒤 정한 시간(원문은 초) 안에 명령이 입력되지 않으면 셸이 끝납니다(셸은 이 값의 상한을 넣어 컴파일될 수 있습니다). 0이면 시간 제한이 없습니다.

관련 개념

  • 공백 해석

Bourne 셸의 미리 정의된 특수 변수

여러 변수에 특별한 뜻이 있습니다. 다음 변수는 Bourne 셸만 설정합니다.

변수 설명
$@ $1부터 위치 매개변수를 펼칩니다. 각 매개변수는 스페이스로 구분됩니다. $@를 큰따옴표로 감싸면 각 위치 매개변수를 별도 문자열로 봅니다. 위치 매개변수가 없으면 따옴표 없는 빈 문자열로 펼칩니다.
$* $1부터 위치 매개변수를 펼칩니다. 각 매개변수를 IFS 값의 첫 문자로 구분합니다. $*를 큰따옴표로 감싸면 위치 매개변수 값들을 큰따옴표 안에 넣으며, 각 값은 IFS의 첫 문자로 구분됩니다.
$# 셸에 넘긴 위치 매개변수 수(셸 프로시저 이름 자체는 세지 않음). 설정된 위치 매개변수 가운데 가장 큰 번호가 됩니다. 주된 용도는 필요한 인수 개수 확인입니다. 셸에서는 $0부터 $9까지만 접근할 수 있습니다.
$? 마지막으로 실행한 명령의 종료 값(십진 문자열). 대부분의 명령은 성공하면 0을 돌려줍니다. 셸 자신은 종료 값으로 $?의 현재 값을 돌려줍니다.
$$ 현재 프로세스의 프로세스 번호. 프로세스 번호는 존재하는 모든 프로세스 사이에서 고유하므로 임시 파일의 고유한 이름을 만드는 데 자주 씁니다.
$! & 종결자로 백그라운드에서 마지막으로 실행한 프로세스의 번호
$- 셸에 현재 설정된 실행 플래그 이름으로 된 문자열

$$로 임시 파일 전용 디렉터리에 임시 파일을 만드는 권장 방법은 다음과 같습니다.

text
temp=/tmp/$$
ls >$temp
. . .
rm $temp

관련 개념

  • Bourne 셸의 위치 매개변수

공백 해석

셸은 변수와 명령 치환을 한 뒤 결과에서 내부 필드 구분자(IFS 셸 변수에 정의한 것)를 찾습니다.

셸은 이 문자를 하나 이상 찾을 때마다 줄을 서로 다른 단어로 나누고, 각 단어를 스페이스 하나로 구분합니다. 그런 다음 명시적인 빈 인수(""나 '')는 유지하고 암시적인 빈 인수(값이 없는 매개변수에서 생긴 것)는 버립니다.

관련 참조

  • Bourne 셸이 쓰는 변수
영어 원문

Bourne shell

The Bourne shell is an interactive command interpreter and command programming language.

The bsh command runs the Bourne shell.

The Bourne shell can be run either as a login shell or as a subshell under the login shell. Only the login command can call the Bourne shell as a login shell. It does this by using a special form of the bsh command name: -bsh. When called with an initial hyphen (-), the shell first reads and runs commands found in the system /etc/profile file and your $HOME/.profile, if one exists. The /etc/profile file sets variables needed by all users. Finally, the shell is ready to read commands from your standard input.

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 are ignored. The shell then reads the commands. If either the -c or -s flag is used, do not specify a script.

Related concepts

Available shells The following are the shells that are provided with AIX.

Bourne shell environment

All variables (with their associated values) known to a command at the beginning of its execution constitute its environment. This environment includes variables that a command inherits from its parent process and variables specified as keyword parameters on the command line that calls the command.

The shell passes to its child processes the variables named as arguments to the built-in export command. This command places the named variables in the environments of both the shell and all its future child processes.

Keyword parameters are variable-value pairs that appear in the form of assignments, normally before the procedure name on a command line (but see also the flag for the set command). These variables are placed in the environment of the procedure being called.

See the following examples:

  • Consider the following procedure, which displays the values of two variables (saved in a command file named key_command):
text
# key_command
echo $a $b

The following command lines produce the output shown:

text
Input                              Output
a=key1   b=key2  key_command       key1 key2
a=tom    b=john  key_command       tom john

A procedure's keyword parameters are not included in the parameter count stored in $#.

A procedure can access the values of any variables in its environment. If it changes any of these values, however, the changes are not reflected in the shell environment. The changes are local to the procedure in question. To place the changes in the environment that the procedure passes to its child processes, you must export the new values within that procedure.

See the following examples:

  • To obtain a list of variables that are exportable from the current shell, type the following:
text
export
  • To obtain a list of read-only variables from the current shell, type the following:
text
readonly
  • To obtain a list of variable-value pairs in the current environment, type the following:
text
env

For more information about user environments, see /etc/environment file.

Conditional substitution in the Bourne shell

Normally, the shell replaces the expression $Variable with the string value assigned to the Variable variable, if there is one. However, there is a special notation that allows conditional substitution, depending on whether the variable is set or not null, or both.

By definition, a variable is set if it has ever been assigned a value. The value of a variable can be the null string, which you can assign to a variable in any one of the following ways:

  • A= bcd=""
  • Efg=’’ — Assigns the null string to the A, bcd, and Efg.
  • set ’’ "" — Sets the first and second positional parameters to the null string and unsets all other positional parameters.

The following is a list of the available expressions you can use to perform conditional substitution:

  • ${Variable``- String} — If the variable is set, substitute the Variable value in place of this expression. Otherwise, replace this expression with the String value.
  • ${Variable:-String} — If the variable is set and not null, substitute the Variable value in place of this expression. Otherwise, replace this expression with the String value.
  • ${Variable=String} — If the variable is set, substitute the Variable value in place of this expression. Otherwise, set the Variable value to the String value and then substitute the Variable value in place of this expression. You cannot assign values to positional parameters in this fashion.
  • ${Variable:=String} — If the variable is set and not null, substitute the Variable value in place of this expression. Otherwise, set the Variable value to the String value and then substitute the Variable value in place of this expression. You cannot assign values to positional parameters in this fashion.
  • ${Variable?String} — If the variable is set, substitute the Variable value in place of this expression. Otherwise, display a message of the following form: Variable: String and exit from the current shell (unless the shell is the login shell). If you do not specify a value for the String variable, the shell displays the following message: Variable: parameter null or not set
  • ${Variable:?String} — If the variable is set and not null, substitute the Variable value in place of this expression. Otherwise, display a message of the following form: Variable: String and exit from the current shell (unless the shell is the login shell). If you do not specify the String value, the shell displays the following message: Variable: parameter null or not set
  • ${Variable``+String} — If the variable is set, substitute the String value in place of this expression. Otherwise, substitute the null string.
  • ${Variable:+String} — If the variable is set and not null, substitute the String value in place of this expression. Otherwise, substitute the null string.

In conditional substitution, the shell does not evaluate the String variable until the shell uses this variable as a substituted string. Thus, in the following example, the shell executes the pwd command only if d is not set or is null:

text
echo ${d:-`pwd`}

Related concepts

User-defined variables in the Bourne shell The Bourne shell recognizes alphanumeric variables to which string values can be assigned.

Positional parameters in the Bourne shell

When you run a shell procedure, the shell implicitly creates positional parameters that reference each word on the command line by its position on the command line.

The word in position 0 (the procedure name) is called $0, the next word (the first parameter) is called $1, and so on, up to $9. To refer to command line parameters numbered higher than 9, use the built-in shift command.

You can reset the values of the positional parameters explicitly by using the built-in set command.

Note: When an argument for a position is not specified, its positional parameter is set to null. Positional parameters are global and can be passed to nested shell procedures.

Related concepts

User-defined variables in the Bourne shell The Bourne shell recognizes alphanumeric variables to which string values can be assigned.

Related reference

Predefined special variables in the Bourne shell Several variables have special meanings. The following variables are set only by the Bourne shell:

File name substitution in the Bourne shell

The Bourne shell permits you to perform file name substitutions.

Command parameters are often file names. You can automatically produce a list of file names as parameters on a command line. To do this, specify a character that the shell recognizes as a pattern-matching character. When a command includes such a character, the shell replaces it with the file names in a directory.

Note: The Bourne shell does not support file name expansion based on equivalence classification of characters.

Most characters in such a pattern match themselves, but you can also use some special pattern-matching characters in your pattern. These special characters are as follows:

  • * — Matches any string, including the null string
  • ? — Matches any one character
  • [ . . . ] — Matches any one of the characters enclosed in square brackets
  • [! . . . ] — Matches any character within square brackets other than one of the characters that follow the exclamation mark

Within square brackets, a pair of characters separated by a hyphen (-) specifies the set of all characters lexicographically within the inclusive range of that pair, according to the binary ordering of character values.

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

text
.*file

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

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

Input and output redirection in the Bourne shell

There are redirection options that can be used in commands.

In general, most commands do not know whether their input or output is associated with the keyboard, the display screen, or a file. Thus, a command can be used conveniently either at the keyboard or in a pipeline.

The following redirection options can appear anywhere in a simple command. They can also precede or follow a command, but are not passed to the command.

  • <File — Uses the specified file as standard input.
  • >File — Uses the specified file as standard output. Creates the file if it does not exist; otherwise, truncates it to zero length.
  • > >File — Uses the specified file as standard output. Creates the file if it does not exist; otherwise, adds the output to the end of the file.
  • <<[-]eofstr — Reads as standard input all lines from the eofstr variable up to a line containing only eofstr or up to an end-of-file character. If any character in the eofstr variable is quoted, the shell does not expand or interpret any characters in the input lines. Otherwise, it performs variable and command substitution and ignores a quoted newline character (\newline). Use a backslash (\) to quote characters within the eofstr variable or within the input lines. If you add a hyphen (-) to the << redirection option, then all leading tabs are stripped from the eofstr variable and from the input lines.
  • <&Digit — Associates standard input with the file descriptor specified by the Digit variable.
  • >&Digit — Associates standard output with the file descriptor specified by the Digit variable.
  • <&- — Closes standard input.
  • >&- — Closes standard output.
  • Note: The restricted shell does not allow output redirection.

For more information about redirection, see Input and output redirection.

List of Bourne shell built-in commands

The following is a list of Bourne shell built-in commands.

  • : — Returns a zero exit value
  • . — Reads and executes commands from a file parameter and then returns.
  • break — Exits from the enclosing for, while, or until command loops, if any.
  • cd — Changes the current directory to the specified directory.
  • continue — Resumes the next iteration of the enclosing for, while, or until command loops.
  • echo — Writes character strings to standard output.
  • eval — Reads the arguments as input to the shell and executes the resulting command or commands.
  • exec — Executes the command specified by the Argument parameter, instead of this shell, without creating a new process.
  • exit — Exits the shell whose exit status is specified by the n parameter.
  • export — Marks names for automatic export to the environment of subsequently executed commands.
  • hash — Finds and remembers the location in the search path of specified commands.
  • pwd — Displays the current directory.
  • read — Reads one line from standard input.
  • readonly — Marks name specified by Name parameter as read-only.
  • return — Causes a function to exit with a specified return value.
  • set — Controls the display of various parameters to standard output.
  • shift — Shifts command-line arguments to the left.
  • test — Evaluates conditional expressions.
  • times — Displays the accumulated user and system times for processes run from the shell.
  • trap — Runs a specified command when the shell receives a specified signal or signals.
  • type — Interprets how the shell would interpret a specified name as a command name.
  • ulimit — Displays or adjusts allocated shell resources.
  • umask — Determines file permissions.
  • unset — Removes the variable or function corresponding to a specified name.
  • wait — Waits for the specified child process to end and reports its termination status.

Related reference

Bourne shell built-in commands Special commands are built into the Bourne shell and run in the shell process.

Bourne shell commands

You can issue commands in the Bourne shell.

When you issue a command in the Bourne shell, it first evaluates the command and makes all indicated substitutions. It then runs the command provided that:

  • The command name is a Bourne shell special built-in command. OR

  • The command name matches the name of a defined function. If this is the case, the shell sets the positional parameters to the parameters of the function.

If the command name matches neither a built-in command nor the name of a defined function and the command names an executable file that is a compiled (binary) program, the shell (as parent) creates a new (child) process that immediately runs the program. If the file is marked executable but is not a compiled program, the shell assumes that it is a shell procedure. In this case, the shell creates another instance of itself (a subshell), to read the file and execute the commands included in it. The shell also runs a parenthesized command in a subshell. To the user, a compiled program is run in exactly the same way as a shell procedure. The shell normally searches for commands in file system directories in this order:

  1. /usr/bin

  2. /etc

  3. /usr/sbin

  4. /usr/ucb

  5. $HOME/bin

  6. /usr/bin/X11

  7. /sbin

  8. Current directory

The shell searches each directory, in turn, continuing with the next directory if it fails to find the command.

Note: The PATH variable determines the order in which the shell searches directories. You can change the particular sequence of directories searched by resetting the PATH variable.

If you give a specific path name when you run a command (for example, /usr/bin/sort), the shell does not search any directories other than the one you specify. If the command name contains a slash (/), the shell does not use the search path.

You can give a full path name that begins with the root directory (such as /usr/bin/sort). You can also specify a path name relative to the current directory. If you specify, for example:

text
bin/myfile

the shell looks in the current directory for a directory named bin and in that directory for the file myfile.

Note: The restricted shell does not run commands containing a slash (/).

The shell remembers the location in the search path of each executed command (to avoid unnecessary exec commands later). If it finds the command in a relative directory (one whose name does not begin with /), the shell must redetermine the command's location whenever the current directory changes. The shell forgets all remembered locations each time you change the PATH variable or run the hash -r command.

Character quotation:

Many characters have a special meaning to the shell. Sometimes you want to conceal that meaning. Single (’) and double (") quotation marks surrounding a string, or a backslash (\) before a single character allow you to conceal the character's meaning.

All characters (except the enclosing single quotation marks) are taken literally, with any special meaning removed. Thus, the command:

text
stuff=’echo $? $*; ls * | wc’

assigns the literal string echo $? $*; ls * | wc to the variable stuff. The shell does not execute the echo, ls, and wc commands or expand the $? and $* variables and the asterisk (*) special character.

Within double quotation marks, the special meaning of the dollar sign ($), backquote ('), and double quotation (") characters remains in effect, while all other characters are taken literally. Thus, within double quotation marks, command and variable substitution takes place. In addition, the quotation marks do not affect the commands within a command substitution that is part of the quoted string, so characters there retain their special meanings.

Consider the following sequence:

text
ls *
file1 file2 file3
message="This directory contains `ls * ` "
echo $message
This directory contains file1 file2 file3

This shows that the asterisk (*) special character inside the command substitution was expanded.

To hide the special meaning of the dollar sign ($), backquote ('), and double quotation (") characters within double quotation marks, precede these characters with a backslash (\). When you do not use double quotation marks, preceding a character with a backslash is equivalent to placing it within single quotation marks. Therefore, a backslash immediately preceding a newline character (that is, a backslash at the end of the line) hides the newline character and allows you to continue the command line on the next physical line.

Signal handling:

The shell ignores INTERRUPT and QUIT signals for an invoked command if the command is terminated with an ampersand (&); that is, if it is running in the background. Otherwise, signals have the values inherited by the shell from its parent, with the exception of the SEGMENTATION VIOLATION signal.

For more information, see the Bourne shell built-in trap command.

Bourne shell compound commands:

A compound command is one of the following.

  • Pipeline (one or more simple commands separated by the pipe (|) symbol)

  • List of simple commands

  • Command beginning with a reserved word

  • Command beginning with the control operator left parenthesis (()

Unless otherwise stated, the value returned by a compound command is that of the last simple command executed.

Reserved words:

The following reserved words for the Bourne shell are recognized only when they appear without quotation marks as the first word of a command.

for do done
case esac
if then fi
elif else
while until
{ }
( )
  • forIdentifier [inWord. . .] doList done — Sets the Identifier parameter to the word or words specified by the Word parameter (one at a time) and runs the commands specified in the List parameter. If you omit in Word. . ., then the for command runs the List parameter for each positional parameter that is set, and processing ends when all positional parameters have been used.
  • case Word in Pattern

[|Pattern] . . . ) List;; [Pattern [|Pattern] . . . ) List;;] . . . esac Runs the commands specified in the List parameter that are associated with the first Pattern parameter that matches the value of the Word parameter. Uses the same character-matching notation in patterns that are used for file name substitution, except that a slash (/), leading dot (.), or a dot immediately following a slash (/.) do not need to match explicitly.

if List then List [elif List then List] . . . [else List] fi Runs the commands specified in the List parameter following the if command. If the command returns a zero exit value, the shell runs the List parameter following the first then command. Otherwise, it runs the List parameter following the elif command (if it exists). If this exit value is zero, the shell runs the List parameter following the next then command. If the command returns a nonzero exit value, the shell runs the List parameter following the else command (if it exists). If no else List or then List is performed, the if command returns a zero exit value. while List do List done Runs the commands specified in the List parameter following the while command. If the exit value of the last command in the while List is zero, the shell runs the List parameter following the do command. It continues looping through the lists until the exit value of the last command in the while List is nonzero. If no commands in the do List are performed, the while command returns a zero exit value.

until List do List done Runs the commands specified in the List parameter following the until command. If the exit value of the last command in the until List is nonzero, runs the List following the do command. Continues looping through the lists until the exit value of the last command in the until List is zero. If no commands in the do List are performed, the until command returns a zero exit value.

( List ) Runs the commands in the List parameter in a subshell.

{ List; } Runs the commands in the List parameter in the current shell process and does not start a subshell.

Name () Defines a function that is referenced by the Name parameter. The body of the function is the list of commands between the braces specified by the List parameter.

Bourne shell built-in commands:

Special commands are built into the Bourne shell and run in the shell process.

Unless otherwise indicated, output is written to file descriptor 1 (standard output) and the exit status is 0 (zero) if the command does not contain any syntax errors. Input and output redirection is permitted.

The following special commands are treated somewhat differently from other special built-in commands:

continue readonly wait
eval return

The Bourne shell processes these commands as follows:

  • Keyword parameter assignment lists preceding the command remain in effect when the command completes.

  • I/O redirections are processed after parameter assignments.

  • Errors in a shell script cause the script to stop processing.

Related reference

List of Bourne shell built-in commands The following is a list of Bourne shell built-in commands.

Special command descriptions:

The Bourne shell provides the following special built-in commands.

  • : — Returns a zero exit value.
  • . File — Reads and runs commands from the File parameter and returns. Does not start a subshell. The shell uses the search path specified by the PATH variable to find the directory containing the specified file.
  • break [ n ] — Exits from the enclosing for, while, or until command loops, if any. If you specify the n variable, the break command breaks the number of levels specified by the n variable.
  • continue [ n ] — Resumes the next iteration of the enclosing for, while, or until command loops. If you specify the n variable, the command resumes at the nth enclosing loop.
  • cd Directory ] — Changes the current directory to Directory. If you do not specify Directory, the value of the HOME shell variable is used. The CDPATH shell variable defines the search path for Directory. CDPATH is a colon-separated list of alternative directory names. A null path name specifies the current directory (which is the default path). This null path name appears immediately after the equal sign in the assignment or between the colon delimiters anywhere else in the path list. If Directory begins with a slash (/), the shell does not use the search path. Otherwise, the shell searches each directory in the CDPATH shell variable. Note: The restricted shell cannot run the cd shell command.
  • echo String . . . ] — Writes character strings to standard output. See the echo command for usage and parameter information. The -n flag is not supported.
  • eval [ Argument . . . ] — Reads arguments as input to the shell and runs the resulting command or commands.
  • exec [ Argument . . . ] — Runs the command specified by the Argument parameter in place of this shell without creating a new process. Input and output arguments can appear, and if no other arguments appear, cause the shell input or output to be modified. This is not recommended for your login shell.
  • exit [ n ] — Causes a shell to exit with the exit value specified by the n parameter. If you omit this parameter, the exit value is that of the last command executed (the Ctrl-D key sequence also causes a shell to exit). The value of the n parameter can be from 0 to 255, inclusive.
  • export [ Name . . . ] — Marks the specified names for automatic export to the environments of subsequently executed commands. If you do not specify the Name parameter, the export command displays a list of all names that are exported in this shell. You cannot export function names.
  • hash [ -r ][ Command . . . ] — Finds and remembers the location in the search path of each Command specified. The -r flag causes the shell to forget all locations. If you do not specify the flag or any commands, the shell displays information about the remembered commands in the following format: Hits Cost Command Hits indicates the number of times a command has been run by the shell process. Cost is a measure of the work required to locate a command in the search path. Command shows the path names of each specified command. Certain situations require that the stored location of a command be recalculated; for example, the location of a relative path name when the current directory changes. Commands for which that might be done are indicated by an asterisk (*) next to the Hits information. Cost is incremented when the recalculation is done.
  • pwd — Displays the current directory. See the pwd command for a discussion of command options.
  • read [ Name . . . ] — Reads one line from standard input. Assigns the first word in the line to the first Name parameter, the second word to the second Name parameter, and so on, with leftover words assigned to the last Name parameter. This command returns a value of 0 unless it encounters an end-of-file character.
  • readonly [ Name . . . ] — Marks the name specified by the Name parameter as read-only. The value of the name cannot be reset. If you do not specify any Name, the readonly command displays a list of all read-only names.
  • return [ n ] — Causes a function to exit with a return value of n. If you do not specify the n variable, the function returns the status of the last command performed in that function. This command is valid only when run within a shell function.
  • set [ Flag [ Argument

] . . . ] Sets one or more of the following flags: -a Marks for export all variables to which an assignment is performed. If the assignment precedes a command name, the export attribute is effective only for that command execution environment, except when the assignment precedes one of the special built-in commands. In this case, the export attribute persists after the built-in command has completed. If the assignment does not precede a command name, or if the assignment is a result of the operation of the getopts or read commands, the export attribute persists until the variable is unset. -e Exits immediately if all of the following conditions exist for a command:

  • It exits with a return value greater than 0 (zero).

  • It is not part of the compound list of a while, until, or if command.

  • It is not being tested using AND or OR lists.

  • It is not a pipeline preceded by the ! (exclamation point) reserved word. -f Disables file name substitution. -h Locates and remembers the commands called within functions as the functions are defined. (Normally, these commands are located when the function is performed; see the hash command.) -k Places all keyword parameters in the environment for a command, not just those preceding the command name. -n Reads commands but does not run them. To check for shell script syntax errors, use the -n flag. -t Exits after reading and executing one command. -u Treats an unset variable as an error and immediately exits when performing variable substitution. An interactive shell does not exit. -v Displays shell input lines as they are read. -x Displays commands and their arguments before they are run. — Does not change any of the flags. This is useful in setting the $1 positional parameter to a string beginning with a hyphen (-).

Using a plus sign (+) rather than a hyphen (-) unsets flags. You can also specify these flags on the shell command line. The $- special variable contains the current set of flags.

Any Argument to the set command becomes a positional parameter and is assigned, in order, to $1, $2, ..., and so on. If you do not specify a flag or Argument, the set command displays all the names and values of the current shell variables.

shift [n] Shifts command line arguments to the left; that is, reassigns the value of the positional parameters by discarding the current value of $1 and assigning the value of $2 to $1, of $3 to $2, and so on. If there are more than 9 command line arguments, the 10th is assigned to $9 and any that remain are still unassigned (until after another shift). If there are 9 or fewer arguments, the shift command unsets the highest-numbered positional parameter that has a value.

The $0 positional parameter is never shifted. The shift n command is a shorthand notation specifying n number of consecutive shifts. The default value of the n parameter is 1.

test Expression | [ Expression ] Evaluates conditional expressions. See the test command for a discussion of command flags and parameters. The -h flag is not supported by the built-in test command in bsh.

times Displays the accumulated user and system times for processes run from the shell. trap [ Command ] [ n ] . . . Runs the command specified by the Command parameter when the shell receives the signal or signals specified by the n parameter. The trap commands are run in order of signal number. Any attempt to set a trap on a signal that was ignored on entry to the current shell is ineffective. Note: The shell scans the Command parameter once when the trap is set and again when the trap is taken.If you do not specify a command, then all traps specified by the n parameter are reset to their current values. If you specify a null string, this signal is ignored by the shell and by the commands it invokes. If the n parameter is zero (0), the specified command is run when you exit from the shell. If you do not specify either a command or a signal, the trap command displays a list of commands associated with each signal number.

  • type [Name . . . ] — Indicates how the shell would interpret it as a command name for each Name specified.
  • ulimit [-HS] [ -c | -d | -f

| -m | -r | -s | -t |``-u] [limit] Displays or adjusts allocated shell resources. The shell resource settings can be displayed either individually or as a group. The default mode is to display resources set to the soft setting, or the lower bound, as a group.

The setting of shell resources depends on the effective user ID of the current shell. The hard level of a resource can be set only if the effective user ID of the current shell is root. You will get an error if you are not root user and you are attempting to set the hard level of a resource. By default, the root user sets both the hard and soft limits of a particular resource. The root user should therefore be careful in using the -S, -H, or default flag usage of limit settings. Unless you are a root user, you can set only the soft limit of a resource. After a limit has been decreased by a nonroot user, it cannot be increased, even back to the original system limit.

To set a resource limit, select the appropriate flag and the limit value of the new resource, which should be an integer. You can set only one resource limit at a time. If more than one resource flag is specified, you receive undefined results. By default, ulimit with only a new value on the command line sets the file size of the shell. Use of the -f flag is optional.

You can specify the following ulimit command flags: -c Sets or displays core segment for shell. -d Sets or displays data segment for shell. -f Sets or displays file size for shell. -H Sets or displays hard resource limit (root user only). -m Sets or displays memory for shell. -r Sets or displays maximum number of threads per process. -s Sets or displays stack segment for shell. -S Sets or displays soft resource limit. -t Sets or displays CPU time maximum for shell. -u Sets or displays maximum number of processes per user.

umask [nnn] 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. When no value is entered, umask displays the current value. unset [Name . . .] Removes the corresponding variable or function for each name specified by the Name parameter. The PATH, PS1, PS2, MAILCHECK, and IFS shell variables cannot be unset.

wait [n] Waits for the child process whose process number is specified by the n parameter to exit and then returns the exit status of that process. If you do not specify the n parameter, the shell waits for all currently active child processes, and the return value is 0.

Command substitution in the Bourne shell:

Command substitution allows you to capture the output of any command as an argument to another command.

When you place a command line within backquotes (''), the shell first runs the command or commands and then replaces the entire expression, including the backquotes, with the output. This feature is often used to give values to shell variables. For example, the statement:

text
today=`date`

assigns the string representing the current date to the today variable. The following assignment saves, in the files variable, the number of files in the current directory:

text
files=`ls | wc -l`

You can perform command substitution on any command that writes to standard output.

To nest command substitutions, precede each of the nested backquotes with a backslash (\), as in:

text
logmsg=`echo Your login directory is \`pwd\``

You can also give values to shell variables indirectly by using the read special command. This command takes a line from standard input (usually your keyboard) and assigns consecutive words on that line to any variables named. For example:

text
read first init last

takes an input line of the form:

text
J. Q. Public

and has the same effect as if you had typed:

text
first=J. init=Q. last=Public

The read special command assigns any excess words to the last variable.

Variable substitution in the Bourne shell:

The Bourne shell permits you to perform variable substitutions.

The Bourne shell has several mechanisms for creating variables (assigning a string value to a name). Certain variables, positional parameters and keyword parameters are normally set only on a command line. Other variables are simply names to which you or the shell can assign string values.

Related concepts

Unattended terminals All systems are vulnerable if terminals are left logged in and unattended. The most serious problem occurs when a system manager leaves a terminal unattended that has been enabled with root authority. In general, users should log out anytime they leave their terminals.

User-defined variables in the Bourne shell

The Bourne shell recognizes alphanumeric variables to which string values can be assigned.

To assign a string value to a name, type the following:

text
Name=String

A name is a sequence of letters, digits, and underscores that begins with an underscore or a letter. To use the value that you have assigned to a variable, add a dollar sign ($) to the beginning of its name. Thus, the $Name variable yields the value specified by the String variable. Note that no spaces are on either side of the equal sign (=) in an assignment statement. (Positional parameters cannot appear in an assignment statement. You can put more than one assignment on a command line, but remember that the shell performs the assignments from right to left.

If you enclose the String variable with double or single quotation marks (" or ’), the shell does not treat blanks, tabs, semicolons, and newline characters within the string as word delimiters, but it imbeds them literally in the string.

If you enclose the String variable with double quotation marks ("), the shell still recognizes variable names in the string and performs variable substitution; that is, it replaces references to positional parameters and other variable names that are prefaced by dollar sign ($) with their corresponding values, if any. The shell also performs command substitution within strings that are enclosed in double quotation marks.

If you enclose the String variable with single quotation marks (’), the shell does not substitute variables or commands within the string. The following sequence illustrates this difference:

text
You:            num=875
                number1="Add $num"
                number2=’Add $num’
                echo $number1
System:         Add 875
You:            echo $number2
System:         Add $num

The shell does not reinterpret blanks in assignments after variable substitution. Thus, the following assignments result in $first and $second having the same value:

text
first=’a string with embedded blanks’
second=$first

When you reference a variable, you can enclose the variable name (or the digit designating a positional parameter) in braces { } to delimit the variable name from any string following. In particular, if the character immediately following the name is a letter, digit, or underscore, and the variable is not a positional parameter, then the braces are required:

text
You:            a=’This is a’
                echo "${a}n example"
System:         This is an example
You:            echo "$a test"
System:         This is a test

Related concepts

Positional parameters in the Bourne shell When you run a shell procedure, the shell implicitly creates positional parameters that reference each word on the command line by its position on the command line.

Related reference

Conditional substitution in the Bourne shell Normally, the shell replaces the expression $Variable with the string value assigned to the Variable variable, if there is one. However, there is a special notation that allows conditional substitution, depending on whether the variable is set or not null, or both.

Variables used by the Bourne shell:

The shell uses the following variables. Although the shell sets some of them, you can set or reset all of them.

  • CDPATH — Specifies the search path for the cd (change directory) command.
  • HOME — Indicates the name of your login directory, which is the directory that becomes the current directory upon completion of a login. The login program initializes this variable. The cd command uses the value of the $HOME variable as its default value. Using this variable rather than an explicit path name in a shell procedure allows the procedure to be run from a different directory without alterations.
  • IFS — The characters that are IFS (internal field separators), which are the characters that the shell uses during blank interpretation. The shell initially sets the IFS variable to include the blank, tab, and newline characters.
  • LANG — Determines the locale to use for the locale categories when both the LC_ALL variable and the corresponding environment variable (beginning with LC_) do not specify a locale.
  • LC_ALL — Determines the locale to be used to override any values for locale categories specified by the settings of the LANG environment variable or any environment variables beginning with LC_.
  • LC_COLLATE — Defines the collating sequence to use when sorting names and when character ranges occur in patterns.
  • LC_CTYPE — Determines the locale for the interpretation of sequences of bytes of text data as characters (that is, single versus multibyte characters in arguments and input files), which characters are defined as letters (alpha character class), and the behavior of character classes within pattern matching.
  • LC_MESSAGES — Determines the language in which messages should be written.
  • LIBPATH — Specifies the search path for shared libraries.
  • LOGNAME — Specifies your login name, marked readonly in the /etc/profile file.
  • MAIL — Indicates the path name of the file used by the mail system to detect the arrival of new mail. If this variable is set, the shell periodically checks the modification time of this file and displays the value of $MAILMSG if the time changes and the length of the file is greater than 0. Set the MAIL variable in the .profile file. The value normally assigned to it by users of the mail command is /usr/spool/mail/ $LOGNAME.
  • MAILCHECK — The number of seconds that the shell lets elapse before checking again for the arrival of mail in the files specified by the MAILPATH or MAIL variables. The default value is 600 seconds (10 minutes). If you set the MAILCHECK variable to 0, the shell checks before each prompt.
  • MAILMSG — The mail notification message. If you explicitly set the MAILMSG variable to a null string (MAILMSG=""), no message is displayed.
  • MAILPATH — A list of file names separated by colons. If this variable is set, the shell informs you of the arrival of mail in any of the files specified in the list. You can follow each file name by a % and a message to be displayed when mail arrives. Otherwise, the shell uses the value of the MAILMSG variable or, by default, the message [YOU HAVE NEW MAIL]. Note: When the MAILPATH variable is set, these files are checked instead of the file set by the MAIL variable. To check the files set by the MAILPATH variable and the file set by the MAIL variable, specify the MAIL file in your list of MAILPATH files.
  • PATH — The search path for commands, which is an ordered list of directory path names separated by colons. The shell searches these directories in the specified order when it looks for commands. A null string anywhere in the list represents the current directory. The PATH variable is normally initialized in the /etc/environment file, usually to /usr/bin:/etc:/usr/ sbin:/usr/ucb:/usr/bin/X11:/sbin. You can reset this variable to suit your own needs. The PATH variable provided in your .profile file also includes $HOME/bin and your current directory. If you have a project-specific directory of commands, for example, /project/bin, that you want searched before the standard system directories, set your PATH variable as follows: PATH=/project/bin:$PATH The best place to set your PATH variable to a value other than the default value is in your $HOME/.profile file. You cannot reset the PATH variable if you are executing commands under the restricted shell.
  • PS1 — The string to be used as the primary system prompt. An interactive shell displays this prompt string when it expects input. The default value of the PS1 variable is $ followed by a blank space for nonroot users.
  • PS2 — The value of the secondary prompt string. If the shell expects more input when it encounters a newline character in its input, it prompts with the value of the PS2 variable. The default value of the PS2 variable is > followed by a blank space.
  • SHACCT — The name of a file that you own. If this variable is set, the shell writes an accounting record in the file for each shell script executed. You can use accounting programs such as acctcom and acctcms to analyze the data collected.
  • SHELL — The path name of the shell, which is kept in the environment. This variable should be set and exported by the $HOME/.profile file of each restricted login.
  • TIMEOUT — The number of minutes a shell remains inactive before it exits. If this variable is set to a value greater than zero (0), the shell exits if a command is not entered within the prescribed number of seconds after issuing the PS1 prompt. (Note that the shell can be compiled with a maximum boundary that cannot be exceeded for this value.) A value of zero indicates no time limit.

Related concepts

Blank interpretation After the shell performs variable and command substitution, it scans the results for internal field separators (those defined in the IFS shell variable).

Predefined special variables in the Bourne shell:

Several variables have special meanings. The following variables are set only by the Bourne shell:

  • $@ — Expands the positional parameters, beginning with $1. Each parameter is separated by a space. If you place double quotation marks (" ") around $@, the shell considers each positional parameter a separate string. If no positional parameters exist, the Bourne shell expands the statement to an unquoted null string.
  • $* — Expands the positional parameters, beginning with $1. The shell separates each parameter with the first character of the IFS variable value. If you place double quotation marks (" ") around $*, the shell includes the positional parameter values, in double quotation marks. Each value is separated by the first character of the IFS variable.
  • $# — Specifies the number of positional parameters passed to the shell, not counting the name of the shell procedure itself. The $# variable thus yields the number of the highest-numbered positional parameter that is set. One of the primary uses of this variable is to check for the presence of the required number of arguments. Only positional parameters $0 through $9 are accessible through the shell.
  • $? — Specifies the exit value of the last command executed. Its value is a decimal string. Most commands return a value of 0 to indicate successful completion. The shell itself returns the current value of the $? variable as its exit value.
  • $$ — Identifies the process number of the current process. Because process numbers are unique among all existing processes, this string is often used to generate unique names for temporary files. The following example illustrates the recommended practice of creating temporary files in a directory used only for that purpose: temp=/tmp/$$ ls >$temp . . . rm $temp
  • $! — Specifies the process number of the last process run in the background using the & terminator.
  • $- — A string consisting of the names of the execution flags currently set in the shell.

Related concepts

Positional parameters in the Bourne shell When you run a shell procedure, the shell implicitly creates positional parameters that reference each word on the command line by its position on the command line.

Blank interpretation:

After the shell performs variable and command substitution, it scans the results for internal field separators (those defined in the IFS shell variable).

The shell splits the line into distinct words at each place it finds one or more of these characters separating each distinct word with a single space. It then retains explicit null arguments ("" or ’’) and discards implicit null arguments (those resulting from parameters that have no values).

Related reference

Variables used by the Bourne shell The shell uses the following variables. Although the shell sets some of them, you can set or reset all of them.