シェルスクリプトの使用方法

15969 ワード

#!/bin/bash // 쉘 스크립트 프로그램이 bash 프로그램을 실행

ㅇ 변수
name=“hero” // = 주위로 공백 X
age=30

echo ${hero} // 가급적 {}사용하는것이 바람직

$ - The name of the Bash script.
$1 ~ $9 - The first 9 arguments to the Bash script.
$# - How many arguments were passed to the Bash script.
$@ - All the arguments supplied to the Bash script.

$? - The exit status of the most recently run process.(return, 정상인 경우 0, 비정상인 경우 1)
$$ - The process ID of the current script.

$USER - The username of the user running the script.
$HOSTNAME - The hostname of the machine the script is running on.
$RANDOM - Returns a different random number each time is it referred to.

ㅇ 값이나 문자를 읽어보자
read var1 // var1으로 값을 읽는다
read -n3 var1 // 문자 3개만 값을 읽는다
read -p “input data: “ var1 // 문자열 출력 후 read

ㅇ 실행
bash my1.sh
chmod +x my1.sh // 실행권한을 추가
./my1.sh // 이어서 경로에 의한 실행
# // 주석
./my2.sh aaa bbbn // aaa: argument1, bbb: argument2if 조건문 사용법
if [ <some test> ]
then
    <commands>
fi

if [ <some test1> ]; then
<commands 1>
elif [ <some test2> ]; then
<commands 2>
else
<commands 3>
fi

eg)
#!/bin/bash
val=“foo”
if [ $val == “dog” ]; then
    echo “I love dog”
elif [ $val == “cat” ]; then
    echo “my cute cat”
else
    echo “I have no pet”
fi

eg)
#!/bin/bash
n=10
if [ $n -lt 10 ];
then
    echo “one digit number”
else
    echo “two digit number”
fi

ㅇ condition의 종류
-eq	// equal?
-ne	// not equal?
-lt		// less than?
-le 	// less than or equal?
-gt 	// greater than?
-ge 	// greater than or equal?

-z STRING 					// empty string?
-n STRING 					// Not empty string?
STRING == STRING 	// equal?
STRING != STRING 		// not equal?

! EXPR		// not
X && Y 	// and
X || Y 		// or

-e FILE 	// exist?
-r FILE 		// readable?
-w FILE 	// writable?
-x FILE 		// executable?
-h FILE 	// symlink?
-d FILE 	// directory
-s FILE 	// size is > 0 bytes
-f FILE 		// file?for 구문
for (( EXP1; EXP2; EXP3 ))
do
    command1
    command2
    command3
done

for 변수 in [범위]; // 범위 <- 배열 리스트 등
do
	작업할 내용
done

eg)
#!/bin/bash
for val in {1..5}
do
    echo ${val}
done

eg)
for val in $(seq 1 5); // same as {1..5}
do
    echo ${val}
done

ㅇ case: 조건에 따른 명령문
case <variable> in
<pattern1>)
	<commnads>
		;;
<pattern 2>)
	<other commands>
		;;
esac

eg)
case $1 in
hello)
	echo “hello world”
		;;
good)
	echo “good day”
		;;
*) // 나머지 문자
	echo “invalid command”
		;;
esac

eg)
#!/bin/bash
read case;
case $case in
	1) echo “You selected apple”;;
	2) echo “You selected avocado”;;
	3) echo “You selected banana”;;
esac
 

ㅇ function을 만들어보자: 모듈화
#!/bin/bash

test_func() {
	echo “hello, world”
}

ㅇ 함수에서 지역변수 및 파라미터 전달
#!/bin/bash

val=5

function foo(){
	local val=3 // 지역변수
	echo “hello $1 $val” // $1: first argument
}

foo 3 // 3: argument

ㅇ 쉘 스크립트 예제
#!/bin/bash
for i in $( ls ); do // (): evaluation -> ls 명령을 수행하는 것으로 이해 -> ls 명령 수행 결과를 순서대로 출력
	echo item: $i
done

#!/bin/bash
if [ -z “$1];then // arguemnt가 없으면
	echo "usage: $0 directory" // $0: 프로그램 이름
	exit // return값 0: 성공, 1: 실패
fi

eg)
#!/bin/bash
cd /dada &> /dev/null // /dev/null로 보냄
echo rv: $? // $?: 바로 앞에서 수행한 명령의 return값(성공 0, 실패 1)
cd $(pwd) &> /dev/null
echo rv: $?

eg)
#!/bin/bash
counter=0
while [ $counter -lt 10 ]; do
	echo The counter is $counter
	let counter=counter+1 // 변수대입 시 let 사용 주의!
	done
Reference
1.shell scriptを使用します。