티스토리 뷰

IoT 과정

Variable

gaelim 2017. 7. 5. 14:46
반응형

Variables

variable="value string"

variable을 설정시에 equal 기호 전 후로 공백을 넣으면 안된다. 공백은 쉘에서 메타캐릭터이다.

variable의 이름은 숫자로 시작하면안된다.

variable은 언더바 _ 의 특수기호만을 사용가능하다.

variable 값은 shell process 메모리에 저장된다. (Local variable) 따라서 시스템을 껐다키면 사라진다.

variable 값은 기본적 데이터 타입은 문자열string이다.


재밌는 예

$ aster='*'

$ echo $aster   // -> $ echo * -> $ echo [files...]

programs script test.sh xx.sh

$ echo "$aster"  // -> $ echo "*" 

*



Variable Scope

local variable을 export를하면 environment variable이 된다. 이 경우 child process에서 카피되어서 변수를 사용할 수 있다. 이 뜻은, 카피한 후 child process와 parent process의 환경 변수 변경은 연동되지 않는다. 


중괄호의 사용

Concatenating Variables and Strings 

$ last_name=Mudd

$ print $last_nameier

sh: last_nameier: Parameter not set.

$ print "$last_name"ier

Muddier

$ print ${last_name}ier

Muddier


중괄호의 사용

Variable Substrings

filename=utility.ksh

$ ${filename#*.}    왼쪽에서 *. 을 잘라 "ksh" return, ##은 maximum matching 이다.

$ ${filename%.ksh} 오른쪽에서 .ksh을 잘라 "utility" return


실습

$ /home/user13/mycopy

Usage: mycopy file1 file2

$ vi mycopy

"mycopy" 7 lines, 88 characters

#! /usr/bin/sh


if [ $# -lt 2 ]

then

        printf "Usage: ${0##*/} file1 file2\n"

        exit 1

fi


init.d 디렉토리에서 사용된 예 찾아보기

$ grep '$0##\*/' *    //모든 파일중에서 다음과 같은 문법찾기


실습1

$ cat goto.sh

echo $PWD

echo $OLDPWD

cd /home/user13/script/module03

echo $PWD

echo $OLDPWD

cd

$ goto.sh
/home/user13/ch3

/home/user13/script/module03
/home/user13/ch3

-> child shell process의 OLDPWD를 출력하므로, program에 의해 생성된 child shell은 OLDPWD를 가지지 않는다. goto.sh 파일 내용 안에 cd 명령어를 삽입해 다른곳에 들렀다오면 OLDPWD를 출력가능하다.

실습2

$ ex3-4.sh

Size of the system log: 34095 lines

Number of entries in /tmp: 35

Permissions on my .profile: -rw-r--r--

$ cat ex3-4.sh

log_size=$(wc -c /var/adm/syslog/syslog.log | cut -f1 -d" ")

num_objects=$(ll /tmp |wc -l)

perms=$(ll $HOME/.profile | cut -f1 -d" ")


print "Size of the system log: $log_size lines"

print "Number of entries in /tmp: $num_objects"

print "Permissions on my .profile: $perms"


$  cat ex3-4.sh
log_size=$(wc -c /var/adm/syslog/syslog.log)
num_objects=$(ll /tmp |wc -l)
perms=$(ll $HOME/.profile | cut -f1 -d" ")

print "Size of the system log: ${log_size%%/*} lines"   //${log_size%" "}
print "Number of entries in /tmp: $num_objects"
print "Permissions on my .profile: $perms"


반응형

'IoT 과정' 카테고리의 다른 글

Designing Program Output  (0) 2017.07.06
User Input  (0) 2017.07.05
Shell Scripting  (0) 2017.07.05
POSIX Shell Programming  (0) 2017.07.05
HPUX - Managing Users and Groups  (0) 2017.06.26