Download Shell 프로그래밍 3

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
bash points
1
변수
변수의 타입을 명시적으로 선언하지 않지만 문맥에 의해 각 변수
는 세 가지 중 한 타입으로 작동한다.
문자열, 정수, 배열
변수에 저장되는 것은 기본적으로 문자열이다.
이 문자열이 숫자이면 int 타입으로 인식한다.
2
기본
첫 단어는 통상 명령어로 인식한다.
두 번째 이후 단어들은 인자로 인식한다.
이 때 빈 칸과 탭이 단어 구분자로 간주된다.
따옴표로 둘러 쌓인 문자열은 따옴표 안의 (빈칸과 탭을 포함한)
문자열 전체가 하나의 문자열로 간주된다.
3
대입
아래와 같은 표현을 만나면 변수에 값을 대입하는 문장으로 인식
한다.
var=x
= 앞 뒤에는 공백이 없어야 한다.
아래와 같이 적으면 var가 명령어이고 =와 x는 명령어에 주어진
인자들이라고 간주한다.
var = x
4
cp="computer
programming"
변수 cp에 computer
programming 이라는 하나의 문자
열을 저장한다. 저장할 때 따옴표는 제외한다.
echo $cp
우선 변수대치가 일어나 아래와 같은 명령이 된다.
echo computer
programming
첫 번째 단어는 명령어, 그 이후는 차례로 인자로 인식된다.
echo는 인자들을 화면에 차례로 보여주는 명령어다. 보여줄
때 인자들 사이에는 공백문자를 하나씩 삽입한다. 출력은 아
래와 같다.
computer programming
echo "$cp"
computer
programming
Put double quotes around every parameter expansion!
5
test, [ ], [[ ]]
test 는 [ 와 같은 것으로서 명령어이다.
[ a = b ] a, =, b, ] are arguments for the test command.
] 는 [ 명령어에서 요구되는 마지막 인자이다.
[[
[[
]] 는 키워드이다.
]] 가 사용시 에러가 적으며 기능이 많으므로 권장된다.
[[ abc = a* ]] # globbing 사용 가능
[[ abb =~ ab+ ]]
# regular expression 사용 가능
$[a<b]
# [는 명령어, a는 인자, < b는 리디렉션으로 인식
-bash: b: No such file or directory
$ [[ a < b ]] # OK
6
test [ the same
[ a = b ] a, =, b, ] are arguments for the test command.
$ myname='Greg Wooledge' yourname='Someone Else'
$ [ $myname = $yourname ]
-bash: [: too many arguments
$ [ "$myname" = "$yourname" ]
[[ is a key word. Teats arguments specially.
$ [[ $me = $you ]]
# Fine.
Allow pattern matching at the right hand side.
$ [[ $filename = *.png ]] && echo "$filename looks like a PNG file"
7
수식
$ unset a; a=4+5
$ echo $a
4+5
$ let a=4+5
$ echo $a
9
let expr, ((expr))에서는 변수 앞에 $를 붙이지 않아도 된다.
You may use spaces, parentheses and so forth, if you quote the
expression:
$ let a='(5+2)*3'
8
Operators such as ==, <, > and so on cause a comparison to
be performed, inside an arithmetic evaluation.
$ if (($a == 21)); then echo 'Blackjack!'; fi
If the comparison is "true"
(for example, 10 > 2 is true in arithmetic -- but not in strings!)
9
$ (( i=10 )); while (( i > 0 ))
> do echo "$i empty cans of beer."
> (( i-- ))
> done
$ for (( i=10; i > 0; i-- ))
> do echo "$i empty cans of beer."
> done
$ for i in {10..1}
> do echo "$i empty cans of beer."
> done
10
$ echo "I am $LOGNAME" # 겹따옴표
I am lhunath
$ echo 'I am $LOGNAME'
# 홑따옴표
I am $LOGNAME
$ # boo
# 주석
$ echo An open\ \ \ space
# \공백문자는 공백으로
An open space
#취급되지 않는다.
(escape!)
$ echo "My computer is $(hostname)" # 명령어 대치
My computer is Lyndir
$ echo boo > file
# 리디렉션
$ echo $(( 5 + 5 )) # 수식
10
$ (( 5 > 0 )) && echo "Five is bigger than zero." # 조건부 실행
Five is bigger than zero.
11
types of commands
builtins, executables, keywords, functions, aliases.
Keywords are quite like builtins, but the main difference is that
special parsing rules apply to them.
!
esac
select
}
case
fi
then
[[
do
for
until
]]
done
function
while
elif
if
time
else
in
{
12
command 종류를 알려면 type 명령을 사용한다.
$type cd
cd is a shell builtin
$type ls
ls 은/는 `ls --color=auto' 의 별칭
$type cat
cat is hashed (/bin/cat)
$
13
도움말
• builtin 명령어의 사용법을 보려면 bash에게 help를 요청한다.
$help cd | head -2
cd: cd [-L|[-P [-e]]] [dir]
Change the shell working directory.
• executible 명령어 (외장명령어)의 사용법을 보려면 명령어를 실행시
키면서 --help 옵션을 준다.
$cat --help | head -2
사용법: cat [<옵션>]... [<파일>]...
Concatenate FILE(s), or standard input, to standard output.
$
14
Expansion
means that the shell replaces the parameter by its content.
also called substitution.
15
따옴표 내에서는 특수문자가 특수한 의미를 잃는다.
겹따옴표 내에 있는 홑따옴표는 그 특수한 의미를 잃는다.
$ echo "'$USER', '$USERs', '${USER}s'"
'lhunath', '', 'lhunaths'
16
Pattern
A pattern is a string with a special format designed to match filenames, or to
check, classify or validate data strings.
globs, regular expression
Glob
*: Matches any string, including the null string.
?: Matches any single character.
[...]: Matches any one of the enclosed characters.
$ ls
a abc b c
$ echo *
a abc b c
$ echo a*
a abc
echo a* is replaced by the statement echo a abc, which is then executed.
17
When a glob is used to match _filenames_, the * and ?
characters cannot match a slash (/) character.
So, for instance, the glob */bin might match foo/bin but it
cannot match /usr/local/bin.
18
filenames generated by a glob will
not be split
$ ls
a b.txt # 전체가 하나의 파일 이름일 때
$ for file in `ls`; do rm "$file"; done
rm: cannot remove `a': No such file or directory
rm: cannot remove `b.txt': No such file or directory
$ for file in *; do rm "$file"; done
$ ls
19
$ filename="somefile.jpg"
$ if [[ $filename = *.jpg ]]; then
use a variable to store your regex
20
command grouping
command grouping { commands; }
(Note: don't forget that you need a semicolon or newline
before the closing curly brace!)
cd "$appdir" || { echo "Please create the appdir and try
again" >&2; exit 1; }
21
always avoid using ls
$ files=$(ls) # BAD, BAD, BAD!
$ files=($(ls)) # STILL BAD!
$ files=(*)
# Good!
22
$ echo "The first name is: ${names[0]}"
$ echo "The second name is: ${names[1]}"
$ names=("Bob" "Peter" "$USER" "Big Bad John") # 배열
$ for name in "${names[@]}"; do echo "$name"; done
23
$ names=("Bob" "Peter" "$USER" "Big Bad John")
$ ( IFS=,; echo "Today's contestants are: ${names[*]}" ) # subshell
Today's contestants are: Bob,Peter,lhunath,Big Bad John
$ names=("Bob" "Peter" "$USER" "Big Bad John")
$ printf "%s\n" "${names[@]}"
Bob
Peter
lhunath
Big Bad John
$ array=(a b c)
$ echo ${#array[@]}
3
24
$ indexedArray=( "one" "two" )
$ declare -A associativeArray=( ["foo"]="bar" ["alpha"]="omega" )
$ index=0 key="foo"
$ echo "${indexedArray[$index]}"
one
$ echo "${indexedArray[index]}"
one
$ echo "${indexedArray[index + 1]}"
two
$ echo "${associativeArray[$key]}"
bar
$ echo "${associativeArray[key]}"
$ echo "${associativeArray[key + 1]}"
25
Input And Output
Inputs
•
•
•
•
•
Command-line arguments
Environment variables
Files
Anything else a File Descriptor can point to
(pipes, terminals, sockets, etc.).
26
File Descriptor
File Descriptor
• A numeric index referring to one of a process's open files.
• The way programs refer to files, or to other resources that
work like files (such as pipes, devices, sockets, or
terminals)
Each command has at least three basic descriptors
Standard Input (stdin): File Descriptor 0
Standard Output (stdout): File Descriptor 1
Standard Error (stderr): File Descriptor 2
27
use input redirection than cat pipe!
it is often best simply to have your application read from stdin
28
Here Document
Heredocs are useful if you're trying to embed short blocks of
multi-line data inside your script.
stdin to a command.
(Embedding larger blocks is bad practice)
You should keep your logic (your code) and your input
(your data) separated, preferably in different files.
29
The pipe operator creates a subshell environment for each
command
30
Process Substitution
$ diff -y <(head -n 1 .dictionary) <(tail -n 1 .dictionary)
$ echo diff -y <(head -n 1 .dictionary) <(tail -n 1 .dictionary)
diff -y /dev/fd/63 /dev/fd/62
They're perfect for common short commands like diff that
need filenames for their input sources.
31
Subshells
$ (cd /tmp || exit 1; date > timestamp)
$ pwd
/home/lhunath
32
Jobs
jobs are implemented as "process groups",
33
DON'T EVER parse the output of ls! --> Bash tests
DON'T EVER test or filter filenames with grep! --> Globbing
Don't use cat to feed a single file's content to a filter -->
Reditection
34