[펌]IPv4 가 금방 고갈 된다..

ITWeb/스크랩 2009. 1. 3. 22:05
요즘 들어 많이 보게 되는 기사 이다..
예전에도 찾아 봤었는데.. 나의 기억력의 한계는 정말.. ㅜ.ㅜ;;
암튼.. 이 참에.. 기냥.. 또 펌질을 하고 있다 펌질 하면서 읽어 보고 그러는 거지 뭐 있겠어.. ㅋ
암튼.. 나중에는 IP 외우기도 힘들어 지겠군.. ㅋ


원본 문서 : http://ko.wikipedia.org/wiki/IPv6

IPv6

위키백과 ― 우리 모두의 백과사전.

인터넷 프로토콜 스위트
응용 계층 FTP, HTTP, HTTPS, IMAP, IRC, NNTP, POP3,
SMTP, SIP, SNMP, SSH, UUCP, DNS...
전송 계층 TCP, UDP, SCTP, DCCP, ...
네트워크 계층 IP, IPv4, IPv6, ICMP, ARP, IGMP, ...
데이터링크 계층 이더넷, FDDI, PPP, ...
물리적 계층 RS-232, EIA-422, RS-449, EIA-485...

IPv6Internet Protocol version 6의 준말이다.

IPv6는 인터넷 프로토콜 스택 중 네트워크 계층의 프로토콜로써 version 6 Internet Protocol로 제정된 차세대 인터넷 프로토콜을 말한다. 인터넷(Internet)은 IPv4 프로토콜로 구축되어 왔으나 IPv4 프로토콜의 한계점으로 인해 지속적인 인터넷 발전에 문제가 예상되어 이에 대한 대안으로써 IPv6 프로토콜을 제정하였다.

목차

[숨기기]

[편집] 역사

2004년 12월 현재 IPv4의 43억개 주소 가운데 약 40%인 17억개의 주소만이 남아 있으며, 대한민국에서 할당 받은 34,081,024개의 IPv4 주소 가운데 99.69%인 33,974,528개가 할당되어 사용되고 있다. IPv4 주소는 빠른 속도로 고갈되어 가고 있으며, 인터넷에 접속된 컴퓨터는 기하급수적인 속도로 증가하고 있다. 또한 모자라는 주소를 더 많은 네트워크에 할당하기 위해 네트워크 프래그멘테이션(network fragmentation)은 지속적으로 증가하여 라우터에 많은 부담을 주고 있다.

그러므로 인터넷의 주소 고갈과 네트워크 프래그멘테이션 문제를 해결하고 인터넷에 확장성과 데이터 보안을 강화하기 위해 IPv6가 제안되었다.

IPv6는 Xerox 팔로 알토 연구소에서 개발하고, 1994년 IETF가 채택하였다. 처음에는 IP Next Generation (IPng)라고 불렀다.

2005년 12월 현재 IPv6는 매우 작은 네트워크에 한해 시험적으로 사용하고 있으며, 인터넷의 나머지 부분은 IPv4 프로토콜로 작동하고 있다. 대한민국 정부는 2010년까지 국내 인터넷 주소 체계를 IPv6로 전환할 것이라고 예고했다.

[편집] 특성

IPv6와 기존 IPv4 사이의 가장 큰 차이점은 바로 IP 주소의 길이가 128비트로 늘어났다는 점이다. 이는 폭발적으로 늘어나는 인터넷 사용에 대비하기 위한 것이다. 또한 IPv6는 여러가지 새로운 기능을 제공하는 동시에 기존 IPv4와의 호환성을 최대로 하는 방향으로 설계되었다. 때문에 몇몇 예외(FTP, NTPv3 등)를 제외하고 대부분의 네트워크 수준 상위 프로토콜들은 큰 수정 없이 IPv6 상에서 동작할 수 있다. IPv6 프로토콜은 다음과 같은 특성을 지니는 프로토콜로 개발되었다.

  • IP 주소의 확장 : IPv4의 기존 32 비트 주소공간에서 벗어나, IPv6는 128 비트 주소공간을 제공한다.
  • 호스트 주소 자동 설정 : IPv6 호스트는 IPv6 네트워크에 접속하는 순간 자동적으로 네트워크 주소를 부여받는다. 이는 네트워크 관리자로부터 IP 주소를 부여받아 수동으로 설정해야 했던 IPv4에 비해 중요한 이점이다.
  • 패킷 크기 확장 : IPv4에서 패킷 크기는 64킬로바이트로 제한되어 있었다. IPv6의 점보그램 옵션을 사용하면 특정 호스트 사이에는 임의로 큰 크기의 패킷을 주고받을 수 있도록 제한이 없어지게 된다. 따라서 대역폭이 넓은 네트워크를 더 효율적으로 사용할 수 있다.
  • 효율적인 라우팅 : IP 패킷의 처리를 신속하게 할 수 있도록 고정크기의 단순한 헤더를 사용하는 동시에, 확장헤더를 통해 네트워크 기능에 대한 확장 및 옵션기능의 확장이 용이한 구조로 정의하였다.
  • 플로우 레이블링(Flow Labeling) : 플로우 레이블(flow label) 개념을 도입, 특정 트래픽은 별도의 특별한 처리(실시간 통신 등)를 통해 높은 품질의 서비스를 제공할 수 있도록 한다.
  • 인증 및 보안 기능 : 패킷 출처 인증과 데이터 무결성 및 비밀 보장 기능을 IP 프로토콜 체계에 반영하였다. IPv6 확장헤더를 통해 적용할 수 있다.
  • 이동성 : IPv6 호스트는 네트워크의 물리적 위치에 제한받지 않고 같은 주소를 유지하면서도 자유롭게 이동할 수 있다. 이와 같은 모바일 IPv6는 RFC 3775RFC 3776에 기술되어 있다. (그러나, IPv4에도 모바일 IP가 정의되어 있지만 아직 많이 사용되지 않는다는 것을 밝혀둔다.)

[편집] IPv6 주소공간

IPv4는 32비트의 주소공간을 제공함에 반해, IPv6는 128비트의 주소공간을 제공한다.

32비트 주소공간이란, 32 bit로 표현할 수 있는 주소영역을 지칭한다. 32 bit에 의해 생성할 수 있는 모든 IPv4 주소는 232개이다. 약 42.9억개의 주소에 해당한다.

IPv6의 128비트 주소공간은 128 bit로 표현할 수 있는 2128개의 IPv6 주소영역을 지칭한다. 약 3.4x1038개의 주소를 갖는 주소 영역이다.

IPv4 주소에 비해 IPv6 주소는 그 표현 bit 수가 128bit로 IPv4의 32bit에 비해 4배가 되었지만, 생성되는 IPv6 주소공간 영역은 IPv4 주소공간에 비해 296배의 크기를 갖는다.

IPv6 주소공간은 향후 인터넷에 등장할 대량의 유비쿼터스 통신 장치들이 상호 통신을 할 수 있는 주소공간을 제공할 수 있다. 냉장고, TV, AV 스피커, DVD 플레이어, 홈 보안장치, 전화기 등 각 요소 장비들이 지능화하면서 동시에 무선 인터넷 등을 통해 상호 통신할 수 있도록 각 장치(device)에 IPv6 주소를 제공할 수 있다.

128bit의 주소공간은 지표면의 모든 공간에 10m2당 1개씩의 IPv6/48 네트워크를 제공할 수 있을 만큼의 많은 개수를 갖는다. 어떤 사람들은 이 주소가 지나치게 많고, 그렇게 많은 네트워크가 필요하게 될 일은 영원히 없을 거라고 주장하지만, IPv6의 128bit 주소공간은 주소가 바닥나는 것을 막는 것 외에도 네트워크가 여러 개의 작은 단위로 조각나는 것을 막아 라우팅을 빠르게 만들기 위한 목적도 갖는다.

[편집] 주소 표현

IPv6의 128비트 주소공간은 다음과 같이 32자리의 16진수를 4자리씩 끊어 나타낸다.

2001:0db8:85a3:08d3:1319:8a2e:0370:7334

그러나 32자리의 16진수는 사람이 읽고 쓰기에 불편하고, 대부분의 자리가 0의 숫자를 갖게 되므로, 4자리가 모두 0의 숫자를 가질 경우 하나의 0으로 축약하거나, 혹은 아예 연속되는 0의 그룹을 없애고 ':' 만을 남길 수 있다. 따라서 아래의 IPv6 주소들은 모두 같은 주소를 나타낸다.

2001:0DB8:0000:0000:0000:0000:1428:57ab
2001:0DB8:0000:0000:0000::1428:57ab
2001:0DB8:0:0:0:0:1428:57ab
2001:0DB8:0::0:1428:57ab
2001:0DB8::1428:57ab

또한 맨 앞자리의 0도 축약할 수 있다. 따라서 2001:0DB8:02de::0e132001:DB8:2de::e13로 축약할 수 있다.

그러나 0을 축약하고 ':'로 없애는 규칙은 두 번이나 그 이상으로 적용할 수 없다. 만약 두 번 이상 적용하는 것이 허용되어 2001::25de::cade와 같은 표현이 가능하다면, 이 표현은 다음의 네 가지 주소 가운데 어떤 것을 가리키는지 의미가 불분명해질 것이다.

2001:0000:0000:0000:0000:25de:0000:cade
2001:0000:0000:0000:25de:0000:0000:cade
2001:0000:0000:25de:0000:0000:0000:cade
2001:0000:25de:0000:0000:0000:0000:cade

[편집] 네트워크 표현

IPv6 네트워크(혹은 서브넷)는 2의 제곱수를 크기로 갖는 IPv6 주소들의 집합이다. 네트워크 주소는 네트워크 프리픽스 뒤에 프리픽스의 '/' 기호와 함께 비트 수를 붙여서 나타낸다. 2001:1234:5678:9ABC::/642001:1234:5678:9ABC:: 부터 2001:1234:5678:9ABC:FFFF:FFFF:FFFF:FFFF 까지의 주소를 갖는 네트워크를 나타낸다.

[편집] IPv4 주소의 IPv6 형태

기존 네트워크와의 호환성을 위해, IPv4 주소는 다음과 같은 세 가지 방법을 통해 IPv6 주소로 나타낼 수 있다.

  • 표준 IPv6 표기 : IPv4 주소 192.0.2.52는 16진수로 표시하면 0xC0000234가 된다. 이를 그대로 IPv6 주소로 변경하면 0000:0000:0000:0000:0000:0000:C000:0234가 되고, 줄이면 ::C000:234가 된다.
  • IPv4 호환 주소 : IPv4와의 호환성과 가독성을 위해 기존 표기에 '::' 만을 붙여 ::192.0.2.52와 같이 쓸 수 있다. 그러나 이 방법은 더 이상 사용되지 않아 폐기될 예정이다.
  • IPv4 매핑 주소 : IPv6 프로그램에게 IPv4와의 호환성을 유지하기 위해 사용하는 다른 방법으로, 처음 80비트를 0으로 설정하고 다음 16비트를 1로 설정한 후, 나머지 32비트에 IPv4 주소를 기록하는 IPv4 매핑 주소가 존재한다. 이 주소공간에서는 마지막 32비트를 10진수로 표기할 수 있다. 따라서 192.0.2.52::ffff:192.0.2.52와 같이 쓸 수 있다.

[편집] 특수 주소 공간

  •  ::/128 - 이 주소는 모든 값을 0으로 세팅한 특수한 주소이다. 가상적으로만 사용된다.
  •  ::1/128 - 자기 자신의 주소를 가리키는 루프백 주소이다. 프로그램에서 이 주소로 패킷을 전송하면 네트워크는 전송자에게로 패킷을 반송한다. IPv4의 127.0.0.1과 동일하다.
  •  ::/96 - IPv4 호환 주소를 위해 사용되는 주소공간이다.
  •  ::ffff:0:0/96 - IPv4 매핑 주소를 위해 사용되는 주소공간이다.
  • fc00::/7 - IPv6 유니캐스트를 위한 주소공간이다.
  • fe00::/10 - link-local address를 위한 주소공간이다. IPv4의 자동 설정 IP 주소인 169.254.x.x 에 해당한다.
  • fec0::/10 - site-local address를 위한 주소공간이다. 네트워크 내부에서만 유효한 주소이며, 2004년 10월 RFC3879에서 폐기되어 더 이상 사용되지 않는다.
  • ff00::/8 - IPv6 멀티캐스트를 위한 주소공간이다. IPv4의 브로드캐스트는 더 이상 지원되지 않으며, IPv6에서는 대신 멀티캐스트를 사용해야 한다.

[편집] IPv6 표준 문서

  • RFC2460 Internet Protocol, Version 6 (IPv6) Specification
  • RFC3513 Internet Protocol Version 6 (IPv6) Addressing Architecture
  • RFC2461 Neighbor Discovery for IP Version 6 (IPv6)
  • RFC2463 Internet Control Message Protocol (ICMPv6) for the Internet Protocol Version 6 (IPv6) Specification

[편집] IPv6 참고 사이트


:

[펌]man crontab 1,5

Legacy 2008. 12. 31. 15:34
분 시 일 월 요일 유저 명령어 순이다 근데 이걸 왜케 맨날 까먹는 걸까..ㅡㅜ;
가장 많이 쓰는 것도
*/1 이와 같은 구문 이다 매 1분 마다 혹은 매 1시간 마다.. 된장.. 늘 꺼꾸로 써서 오류를 만들어 낸다..
암튼 이제는 쉬운것도 다 까먹는 바보가 되어 가는게 정말 짜증이다.. 흑흑

crontab -l : 등록된 목록 보기
crontab -e : 목록 수정 하기 또는 등록하기

걍 터미널 상에서 쳐봐.. 그럼 뭐라도 나온다..

자주 하는 실 수중 또 하나..
cp, mv 이런 파일이 위치한 path 가 잡혀 있거나 full path 로 실행 시키시길 바란다..
난 늘 같은 실수는 하는 것 같기도 하고.. 바보가 되어서 잊은 것 같기도 하고.. 된장..

만든 shell script 를 실행 하면 잘 된다.. 하지만 crond 가 잘 실행을 못한다..
그럼 빤하다.. 내가 잘 못한거다..

오늘도 역시 한건 했다.. path 생략하고.. 기냥 했다.. 난 바보인가?? ^^;;

*     *   *   *    *  command to be executed
-     -    -    -    -
|     |     |     |     |
|     |     |     |     +----- day of week (0 - 6) (Sunday=0)
|     |     |     +------- month (1 - 12)
|     |     +--------- day of month (1 - 31)
|     +----------- hour (0 - 23)
+------------- min (0 - 59)


CRONTAB(1)							    CRONTAB(1)

NAME

crontab - maintain crontab files for individual users (V3)

SYNOPSIS

crontab [ -u user ] file crontab [ -u user ] { -l | -r | -e }

DESCRIPTION

crontab is the program used to install, deinstall or list the tables used to drive the cron(8) daemon in Vixie Cron. Each user can have their own crontab, and though these are files in /var/spool/cron/crontabs, they are not intended to be edited directly. If the /etc/cron.allow file exists, then you must be listed therein in order to be allowed to use this command. If the /etc/cron.allow file does not exist but the /etc/cron.deny file does exist, then you must not be listed in the /etc/cron.deny file in order to use this command. If neither of these files exists, then depending on site-dependent con- figuration parameters, only the super user will be allowed to use this command, or all users will be able to use this command. For standard Debian systems, all users may use this command. If the -u option is given, it specifies the name of the user whose crontab is to be tweaked. If this option is not given, crontab exam- ines "your" crontab, i.e., the crontab of the person executing the com- mand. Note that su(8) can confuse crontab and that if you are running inside of su(8) you should always use the -u option for safety's sake. The first form of this command is used to install a new crontab from some named file or standard input if the pseudo-filename ``-'' is given. The -l option causes the current crontab to be displayed on standard output. See the note under DEBIAN SPECIFIC below. The -r option causes the current crontab to be removed. The -e option is used to edit the current crontab using the editor specified by the VISUAL or EDITOR environment variables. After you exit from the editor, the modified crontab will be installed automati- cally. If neither of the environment variables is defined, then the default editor /usr/bin/editor is used.

DEBIAN SPECIFIC

The "out-of-the-box" behaviour for crontab -l is to display the three line "DO NOT EDIT THIS FILE" header that is placed at the beginning of the crontab when it is installed. The problem is that it makes the sequence crontab -l | crontab - non-idempotent -- you keep adding copies of the header. This causes pain to scripts that use sed to edit a crontab. Therefore, the default behaviour of the -l option has been changed to not output such header. You may obtain the original behaviour by setting the environment vari- able CRONTAB_NOHEADER to 'N', which will cause the crontab -l command to emit the extraneous header.

SEE ALSO

crontab(5), cron(8)

FILES

/etc/cron.allow /etc/cron.deny

STANDARDS

The crontab command conforms to IEEE Std1003.2-1992 (``POSIX''). This new command syntax differs from previous versions of Vixie Cron, as well as from the classic SVR3 syntax.

DIAGNOSTICS

A fairly informative usage message appears if you run it with a bad command line.

BUGS

Although cron requires that each entry in a crontab end in a newline character, the neither the crontab command nor the cron daemon will detect this error. Instead, the crontab will appear load normally. How- ever, the command will never run. The best choice is to ensure that your crontab has a blank line at the end.

AUTHOR

Paul Vixie <paul@vix.com> 4th Berkeley Distribution 29 December 1993 CRONTAB(1)

 

 


 

:

[펌]bash script

ITWeb/개발일반 2008. 12. 30. 14:45

원본 URL : http://www.linuxconfig.org/Bash_scripting_Tutorial
참고 사이트 : http://www.unix.com/


This bash script tutorial assumes no previous knowledge of bash scripting.As you will soon discover in this quick comprehensive bash scripting guide, learning the bash shell scripting is very easy task. Lets begin this bash scripting tutorial with a simple "Hello World" script.

Recommended Books / Reading on this topic :

Learning the bash Shell: Unix Shell Programming]

Hello World Bash Shell Script

First you need to find out where is your bash interpreter located. Enter the following into your command line:

$ which bash
bash interpreter location: /bin/bash

Open up you favorite text editor ( Here is a tutorial where you can learn how to use vi / vim text editor. ) and a create file called hello_world.sh. Insert the following lines to a file:

<b>NOTE:Every bash shell script in this tutorial starts with shebang:"#!" which is not read as a comment. First line is also a place where you put your interpreter which is in this case: /bin/bash.

Here is our first bash shell script example:

#!/bin/bash
# declare STRING variable
STRING="Hello World"
#print variable on a screen
echo $STRING

Example of simple bash shell script

Navigate to a directory where your hello_world.sh is located and make the file executable:

$ chmod +x hello_world.sh
Make bash shell script executable

Now you are ready to execute your first bash script:

./hello_world.sh
execute bash shell script


Simple Backup bash shell script

#!/bin/bash
tar -czf myhome_directory.tar.gz /home/linuxconfig
Simple Backup bash script

Variables

In this example we declare simple bash variable and print it on the screen ( stdout ) with echo command.

#!/bin/bash
STRING="HELLO WORLD!!!"
echo $STRING
String Variables in bash script

Your backup script and variables:

#!/bin/bash
OF=myhome_directory_$(date +%Y%m%d).tar.gz
tar -czf $OF /home/linuxconfig
Bash backup Script with Variables

Global vs. Local variables

#!/bin/bash
#Define bash global variable
#This variable is global and can be used anywhere in this bash script
VAR="global variable"
function bash {
#Define bash local variable
#This variable is local to bash function only
local VAR="local variable"
echo $VAR
}
echo $VAR
bash
# Note the bash global variable did not change
# "local" is bash reserved word
echo $VAR
Global vs. Local variables in bash script

Passing arguments to the bash script

#!/bin/bash
# use predefined variables to access passed arguments
#echo arguments to the shell
echo $1 $2 $3 ' -> echo $1 $2 $3'

# We can also store arguments from bash command line in special array
args=("$@")
#echo arguments to the shell
echo ${args[0]} ${args[1]} ${args[2]} ' -> args=("$@"); echo ${args[0]} ${args[1]} ${args[2]}'

#use $@ to print out all arguments at once
echo $@ ' -> echo $@'

# use $# variable to print out
# number of arguments passed to the bash script
echo Number of arguments passed: $# ' -> echo Number of arguments passed: $#'
./arguments.sh Bash Scripting Tutorial
Passing arguments to the bash script

Executing shell commands with bash

#!/bin/bash

# use backticks " ` ` " to execute shell command
echo `uname -o`
# executing bash command without backticks
echo uname -o

Executing shell commands with bash

Reading User Input

#!/bin/bash

echo -e "Hi, please type the word: \c "
read  word
echo "The word you entered is: $word"
echo -e "Can you please enter two words? "
read word1 word2
echo "Here is your input: \"$word1\" \"$word2\""
echo -e "How do you feel about bash scripting? "
# read command now stores a reply into the default build-in variable $REPLY
read
echo "You said $REPLY, I'm glad to hear that! "
echo -e "What are your favorite colours ? "
# -a makes read command to read into an array
read -a colours
echo "My favorite colours are also ${colours[0]}, ${colours[1]} and ${colours[2]}:-)"
Reading User Input with bash

Bash Trap Command

#!/bin/bash
# bash trap command
trap bashtrap INT
# bash clear screen command
clear;
# bash trap function is executed when CTRL-C is pressed:
# bash prints message => Executing bash trap subrutine !
bashtrap()
{
    echo "CTRL+C Detected !...executing bash trap !"
}
# for loop from 1/10 to 10/10
for a in `seq 1 10`; do
    echo "$a/10 to Exit." 
    sleep 1;
done
echo "Exit Bash Trap Example!!!"

Arrays

Declare simple bash array

#!/bin/bash
#Declare array with 4 elements
ARRAY=( 'Debian Linux' 'Redhat Linux' Ubuntu Linux )
# get number of elements in the array
ELEMENTS=${#ARRAY[@]}

# echo each element in array 
# for loop
for (( i=0;i<$ELEMENTS;i++)); do
    echo ${ARRAY[${i}]}
done
Declare simple bash array

Read file into bash array

#!/bin/bash
#Declare array 
declare -a ARRAY
#Open file for reading to array
exec 10<bash.txt
let count=0

while read LINE <&10; do

    ARRAY[$count]=$LINE
    ((count++))
done

echo Number of elements: ${#ARRAY[@]}
# echo array's content
echo ${ARRAY[@]}
# close file 
exec 10>&-
Read file into bash array

Bash if/else statements

Simple Bash if/else statement

Please note the spacing inside the [ and ] brackets! Without the spaces, it won't work!

#!/bin/bash
directory="./BashScripting"

# bash check if directory exists
if [ -d $directory ]; then
	echo "Directory exists"
else 
	echo "Directory does not exists"
fi

Bash if else statement

Nested if/else

#!/bin/bash

# Declare variable choice and assign value 4
choice=4
# Print to stdout
 echo "1. Bash"
 echo "2. Scripting"
 echo "3. Tutorial"
 echo -n "Please choose a word [1,2 or 3]? "
# Loop while the variable choice is equal 4
# bash while loop
while [ $choice -eq 4 ]; do

# read user input
read choice
# bash nested if/else
if [ $choice -eq 1 ] ; then

        echo "You have chosen word: Bash"

else                   

        if [ $choice -eq 2 ] ; then
                 echo "You have chosen word: Scripting"
        else
         
                if [ $choice -eq 3 ] ; then
                        echo "You have chosen word: Tutorial"
                else
                        echo "Please make a choice between 1-3 !"
                        echo "1. Bash"
                        echo "2. Scripting"
                        echo "3. Tutorial"
                        echo -n "Please choose a word [1,2 or 3]? "
                        choice=4
                fi   
        fi
fi
done
Nested Bash if else statement

Bash Comparisons

Arithmetic Comparisons

-lt
<
-gt
>
-le
<=
-ge
>=
-eq
==
-ne
!=
#!/bin/bash
# declare integers
NUM1=2
NUM2=2
if [ $NUM1 -eq $NUM2 ]; then
	echo "Both Values are equal"
else 
	echo "Values are NOT equal"
fi
Bash Arithmetic Comparisons - values are equal
#!/bin/bash
# declare integers
NUM1=2
NUM2=1
if [ $NUM1 -eq $NUM2 ]; then
	echo "Both Values are equal"
else 
	echo "Values are NOT equal"
fi
Bash Arithmetic Comparisons - values are NOT equal
#!/bin/bash
# declare integers
NUM1=2
NUM2=1
if   [ $NUM1 -eq $NUM2 ]; then
	echo "Both Values are equal"
elif [ $NUM1 -gt $NUM2 ]; then
	echo "NUM1 is greater then NUM2"
else 
	echo "NUM2 is greater then NUM1"
fi
Bash Arithmetic Comparisons - greater then

String Comparisons

=
equal
 !=
not equal
<
less then
>
greater then
-n s1
string s1 is not empty
-z s1
string s1 is empty
#!/bin/bash
#Declare string S1
S1="Bash"
#Declare string S2
S2="Scripting"
if [ $S1 = $S2 ]; then
	echo "Both Strings are equal"
else 
	echo "Strings are NOT equal"
fi
Bash String Comparisons - values are NOT equal
#!/bin/bash
#Declare string S1
S1="Bash"
#Declare string S2
S2="Bash"
if [ $S1 = $S2 ]; then
	echo "Both Strings are equal"
else 
	echo "Strings are NOT equal"
fi
Bash String Comparisons - values are equal

Bash File Testing

-b filename Block special file
-c filename Special character file
-d directoryname Check for directory existence
-e filename Check for file existence
-f filename Check for regular file existence not a directory
-G filename Check if file exists and is owned by effective group ID.
-g filename true if file exists and is set-group-id.
-k filename Sticky bit
-L filename Symbolic link
-O filename True if file exists and is owned by the effective user id.
-r filename Check if file is a readable
-S filename Check if file is socket
-s filename Check if file is nonzero size
-u filename Check if file set-ser-id bit is set
-w filename Check if file is writable
-x filename Check if file is executable
#!/bin/bash
file="./file"
if [ -e $file ]; then
	echo "File exists"
else 
	echo "File does not exists"
fi
Bash File Testing - File does not exist
Bash File Testing - File exists

Similarly for example we can use while loop to check if file does not exists. This script will sleep until file does exists. Note bash negator "!" which negates the -e option.

#!/bin/bash

while [ ! -e myfile ]; do
# Sleep until file does exists/is created
sleep 1
done

Loops

Bash for loop

#!/bin/bash

# bash for loop
for f in $( ls /var/ ); do
	echo $f
done

Running for loop from bash shell command line:

$ for f in $( ls /var/ ); do echo $f; done
Bash for loop

Bash while loop

#!/bin/bash
COUNT=6
# bash while loop
while [ $COUNT -gt 0 ]; do
	echo Value of count is: $COUNT
	let COUNT=COUNT-1
done
Bash while loop

Bash until loop

#!/bin/bash
COUNT=0
# bash until loop
until [ $COUNT -gt 5 ]; do
        echo Value of count is: $COUNT
        let COUNT=COUNT+1
done
Bash until loop

Control bash loop with <STDIN>

Here is a example of while loop controlled by standard input. Until the redirection chain from STDOUT to STDIN to the read command exists the while loop continues.

#!/bin/bash
# This bash script will locate and replace spaces
# in the filenames
DIR="."
# Controlling a loop with bash read command by redirecting STDOUT as
# a STDIN to while loop
# find will not truncate filenames containing spaces
find $DIR -type f | while read file; do
# using POSIX class [:space:] to find space in the filename
if [[ "$file" = *[[:space:]]* ]]; then
# substitute space with "_" character and consequently rename the file
mv "$file" `echo $file | tr ' ' '_'`
fi;
# end of while loop
done

Bash script to replace spaces in the filenames with _

Bash Functions

!/bin/bash
# BASH FUNCTIONS CAN BE DECLARED IN ANY ORDER
function function_B {
        echo Function B.
}
function function_A {
        echo $1
}
function function_D {
        echo Function D.
}
function function_C {
        echo $1
}
# FUNCTION CALLS
# Pass parameter to function A
function_A "Function A."
function_B
# Pass parameter to function C
function_C "Function C."
function_D
Bash Functions

Bash Select

#!/bin/bash

PS3='Choose one word: ' 

# bash select
select word in "linux" "bash" "scripting" "tutorial" 
do
  echo "The word you have selected is: $word"
# Break, otherwise endless loop
  break  
done

exit 0
Bash Select

Case statement conditional

#!/bin/bash
echo "What is your preferred programming / scripting language"
echo "1) bash"
echo "2) perl"
echo "3) phyton"
echo "4) c++"
echo "5) I do not know !"
read case;
#simple case bash structure
# note in this case $case is variable and does not have to
# be named case this is just an example
case $case in
    1) echo "You selected bash";;
    2) echo "You selected perl";;
    3) echo "You selected phyton";;
    4) echo "You selected c++";;
    5) exit
esac

bash case statement conditional

Bash quotes and quotations

Quotations and quotes are important part of bash and bash scripting. Here are some bash quotes and quotations basics.

Escaping Meta characters

Before we start with quotes and quotations we should know something about escaping meta characters. Escaping will suppress a special meaning of meta characters and therefore meta characters will be read by bash literally. To do this we need to use backslash "\" character. Example:

#!/bin/bash

#Declare bash string variable
BASH_VAR="Bash Script"

# echo variable BASH_VAR
echo $BASH_VAR

#when meta character such us "$" is escaped with "\" it will be read literally
echo \$BASH_VAR 

# backslash has also special meaning and it can be suppressed with yet another "\"
echo "\\"

escaping meta characters in bash

Single quotes

Single quotes in bash will suppress special meaning of every meta characters. Therefore meta characters will be read literally. It is not possible to use another single quote within two single quotes not even if the single quote is escaped by backslash.

#!/bin/bash

#Declare bash string variable
BASH_VAR="Bash Script"

# echo variable BASH_VAR
echo $BASH_VAR

# meta characters special meaning in bash is suppressed when  using single quotes 
echo '$BASH_VAR  "$BASH_VAR"'

Using single quotes in bash

Double Quotes

Double quotes in bash will suppress special meaning of every meta characters except "$", "\" and "`". Any other meta characters will be read literally. It is also possible to use single quote within double quotes. If we need to use double quotes within double quotes bash can read them literally when escaping them with "\". Example:

#!/bin/bash

#Declare bash string variable
BASH_VAR="Bash Script"

# echo variable BASH_VAR
echo $BASH_VAR

# meta characters and its special meaning in bash is 
# suppressed when using double quotes except "$", "\" and "`"

echo "It's $BASH_VAR  and \"$BASH_VAR\" using backticks: `date`"

Using double quotes in bash

Bash quoting with ANSI-C style

There is also another type of quoting and that is ANSI-C. In this type of quoting characters escaped with "\" will gain special meaning according to the ANSI-C standard.

/a
alert (bell)
/b
backspace
/e
an escape character
/f
form feed
/n
newline
/r
carriage return
/t
horizontal tab
/v
vertical tab
\\
backslash
\`
single quote
\nnn
octal value of characters ( see ASCII table )
\xnn
hexadecimal value of characters ( see ASCII table )

The syntax fo ansi-c bash quoting is: $'<your string>' . Here is an example:

#!/bin/bash

# as a example we have used \n as a new line, \x40 is hex value for @
# and \56 is octal value for .
echo $'web: www.linuxconfig.org\nemail: web\x40linuxconfig\56org'

quoting in bash with ansi-c stype

Arithmetic Operations

Simple Bash Addition Calculator Example

#!/bin/bash

let RESULT1=$1+$2
echo $1+$2=$RESULT1 ' -> # let RESULT1=$1+$2'
declare -i RESULT2
RESULT2=$1+$2
echo $1+$2=$RESULT2 ' -> # declare -i RESULT2; RESULT2=$1+$2'
echo $1+$2=$(($1 + $2)) ' -> # $(($1 + $2))'

Bash Addition Calculator

Bash Arithmetics

#!/bin/bash

echo '### let ###'
# bash addition
let ADDITION=3+5
echo "3 + 5 =" $ADDITION

# bash subtraction
let SUBTRACTION=7-8
echo "7 - 8 =" $SUBTRACTION 

# bash multiplication
let MULTIPLICATION=5*8
echo "5 * 8 =" $MULTIPLICATION

# bash division
let DIVISION=4/2
echo "4 / 2 =" $DIVISION

# bash modulus
let MODULUS=9%4
echo "9 % 4 =" $MODULUS

# bash power of two
let POWEROFTWO=2**2
echo "2 ^ 2 =" $POWEROFTWO


echo '### Bash Arithmetic Expansion ###'
# There are two formats for arithmetic expansion: $[ expression ] 
# and $(( expression #)) its your choice which you use

echo 4 + 5 = $((4 + 5))
echo 7 - 7 = $[ 7 - 7 ]
echo 4 x 6 = $((3 * 2))
echo 6 / 3 = $((6 / 3))
echo 8 % 7 = $((8 % 7))
echo 2 ^ 8 = $[ 2 ** 8 ]


echo '### Declare ###'

echo -e "Please enter two numbers \c"
# read user input
read num1 num2
declare -i result
result=$num1+$num2
echo "Result is:$result "

# bash convert binary number 10001
result=2#10001
echo $result

# bash convert octal number 16
result=8#16
echo $result

# bash convert hex number 0xE6A
result=16#E6A
echo $result
Arithmetic Operations


Round floating point number

#!/bin/bash
# get floating point number
floating_point_number=3.3446
echo $floating_point_number
# round floating point number with bash
for bash_rounded_number in $(printf %.0f $floating_point_number); do
echo "Rounded number with bash:" $bash_rounded_number
done

Round floating point number with bash

Bash floating point calculations

#!/bin/bash
# Simple linux bash calculator 
echo "Enter input:" 
read userinput
echo "Result with 2 digits after decimal point:"
echo "scale=2; ${userinput}" | bc 
echo "Result with 10 digits after decimal point:"
echo "scale=10; ${userinput}" | bc 
echo "Result as rounded integer:"
echo $userinput | bc

Bash floating point calculations

Redirections

STDOUT from bash script to STDERR

#!/bin/bash

echo "Redirect this STDOUT to STDERR" 1>&2

To proof that STDOUT is redirected to STDERR we can redirect script's output to file:

STDOUT from bash script to STDERR

STDERR from bash script to STDOUT

#!/bin/bash

cat $1 2>&1

To proof that STDERR is redirected to STDOUT we can redirect script's output to file:

STDERR from bash script to STDOUT

stdout to screen

The simple way to redirect a standard output ( stdout ) is to simply use any command, because by default stdout is automatically redirected to screen.

cat /proc/partitions
bash stdout to screen

stdout to file

Here we use ">" to redirect stdout to a file "partitions.txt".

cat /proc/partitions > partitions.txt
bash stdout to file

stderr to file

In this example you will redirect the standard error ( stderr ) to a file and stdout to a default screen.

grep -r hda6 * . 2> stderr.txt
bash stderr to file

stdout to stderr

In this case the output of a command will be written to the same descriptor as a stderr.

grep -r hda6 * . 1>&2 stderr.txt
bash stdout to stderr

stderr to stdout

In this case the stderr of a command will be written to the same descriptor as a stdout.

grep -r hda6 * . 2>&1 stderr.txt
stderr to stdout

stderr and stdout to file

grep -r hda6 * . &> stderr_and_stdout.txt
stderr and stdout to file
:

LUA - 루아

Legacy 2008. 12. 24. 15:21

루아 이건 또 뭐야??
게임에 워낙에 관심이 없는 나로써는 이 언어에 대해서 아는 바가 전혀 없었다..

그래서 찾아 보았다..
http://ko.wikipedia.org/wiki/루아_(프로그래밍_언어)

이거란다.
게임을 만들때 사용하는 유용한 스크립트 언어라고 한다.

이제 나도 게임을 만들어야 하나???
와이프가 IT에 종사하는 사람을 무지하게 싫어 한다...

지금도 나 한테 속아서 결혼 했다고.. 가끔.. 바가지를.. ㅋ
근데.. 게임 개발을 한다고 하면.. 더더군다나.... OTL;;

이제 죽었구나.. 음냐..
:

[펌]JSTL

ITWeb/개발일반 2008. 12. 24. 15:16
http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/index.html

시간이 없다는 핑계로 또 다시 펌질을.. 하고 있다는.. ㅡ.ㅡ;;

[출처 : 자바지기]
jstl - API : http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/index.html
JSTL

소개

  • J2EE 소형 클라이언트 기술인 JSP(JavaServer Pages)가 지난 몇 년 동안 널리 일반화되면서 독립적인 개발자들은 많은 사용자 정
    의 JSP 태그 라이브러리를 만들었습니다. 이러한 태그 라이브러리는 대부분 서로 다른 목표를 달성하도록 작성되었지만 반복, 조건 등의 일
    반적인 작업을 위한 유사한 솔루션을 제공하는 경향이 있습니다.
    유사하고 일반적이 문제점을 해결하는 독립적인 태그 라이브러리에 대한 필요성을 줄이기 위해 Java Community Process(JSR 52)의 지
    원하에 JSTL(JavaServer Pages Standard Tag Library)이 개발되었습니다. JSTL은 이러한 일반 기능을 처리하는 하나의 표준 솔루션
    을 제공합니다. (말그대로 표준태그라이브러리)
  • JSTL의 주요 강점 중 하나는 서블릿 컨텍스트에 저장된 데이타 같은 애플리케이션 데이타를 액세스 및 조작하는 쉬운 방법을 제공하는 간
    단한 EL을 사용할 수 있다는 것입니다.

EL 에 대하여

설치 방법

  • http://cvs.apache.org/builds/jakarta-taglibs/nightly/ 에서 다운
    \jakarta-taglibs-20051024\jakarta-taglibs\standard\lib
    에서 jstl 과 standard 파일 을 이 두개의 jar 파일을 우리의 웹애플리케이션의 /WEB-INF/lib 폴더에 넣습니다
    그 다음 tld 폴더의 tld 파일을 /WEB-INF/lib/tld 폴더 아래 넣습니다.
  • web.xml 에
     
        <!-- jstl 1.2 taglig -->
         <taglib>
           <taglib-uri>jstl-c</taglib-uri>
           <taglib-location>/WEB-INF/tlds/jstl/c.tld</taglib-location>
        </taglib>
        <taglib>
           <taglib-uri>jstl-fmt</taglib-uri>
           <taglib-location>/WEB-INF/tlds/jstl/fmt.tld</taglib-location>
        </taglib>
        <taglib>
          <taglib-uri>jstl-fn</taglib-uri>
          <taglib-location>/WEB-INF/tlds/jstl/fn.tld</taglib-location>
        </taglib>
        

    를 추가한다.

  • jsp 에 추가
     
         <%@ taglib uri="jstl-c" prefix="c" %>
        <%@ taglib uri="jstl-fmt" prefix="fmt" %>
        <%@ taglib uri="jstl-fn" prefix="fn" %>
         

사용 예(기본 문법)

Area Subfunction Prefix Description
Core Variable support c 변수지원
Core Flow control c 흐름제어
Core URL management c URL 처리
Core Miscellaneous c  
XML Core x XML 코어
XML Flow control x 흐름 제어
XML Transformation x XML 변환
I18n Locale fmt 지역
I18n Message formatting fmt 메시지 형식
I18n Number and date formatting fmt 숫자 및 날짜 형식
Database SQL sql SQL
Functions Collection length fn 콜렉션 처리
Functions String manipulation fn String 처리

http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/index.html 참고

  • 변수지원태그
    set: <c:set var="varName" scope="session" value="someValue">
    var속성은 값을 지정할 변수의 이름
    <c:set t a r g e t ="" property="userName" value="someValue">
    target : 빈 프로퍼티나 맵 값을 설정한다.(Object)
    var와 target을 동시에 사용할 수 없다.
    scope속성은 변수가 위치하는 영역(page,request,session,application)
    value :저장하는 값
    remove :<c:remove var="varName" scope="session">
    var :삭제할 변수의 이름
    scope 속성은 삭제할 변수의 영역
    out : <c:out value="">
    value속성은 출력하려는 값
    catch : <c:catch var="">
    </c:catch>
    예외사항이 한번이라도 발생시 </c:catch>로 점프
    var에 정의 된 객체를 페이지 생존범위에 자동으로 묶어 나중에 var에 정의된 변수이름을 사용할 수 있다.
    예외 발생시
    : var 속성 사용시 exception 객체를 설정.
    <c:catch> 문 밖으로 제어가 떨어진다
 
    <c:set var="num1" value="${20}" />
	<c:set var="num2">
		10.5
	</c:set>
	
	<c:set var="today" value="<%= new java.util.Date()%>" /><br>

	변수 num1 = ${num1} <br>
	변수 num2 = ${num2} <br>
	num1 + num2 = ${num1+num2}<br>
	오늘은 ${today}입니다.
	
	<c:remove var="num1" scope="page" />
	
	<p>
	삭제한 후의  num1=${num1} <br>
	삭제한 후의 num1 + num2 = ${num1 + num2}
   
 
       <c:catch var="myException">
     	It's catch
         <% int x = 10/0; %>
         실행안됨.
       </c:catch>
       <c:if test="${myException != null}">
           발생된 예외는 : ${myException.message} <br>
       </c:if>
     
  • URL 관련
    import : <c:import url=""/>
    url속성에 명기한 파일을 현재 컨텐츠에 포함
    param : <c:param name="" value=""/>
    <jsp:param />과 같은 역할
    url : <c:url value="" var=""/>
    value에 들어있는 상대 경로 뒤에 jsessionid를 추가한다.(쿠키를 사용 못하는 경우)
    var : 옵션 속성으로 url을 참조하기 위해쓴다.
    redirect :<c:redirect url="' context=""/>
    context : url경로의 이름
 
    <c:import url="Header.jsp" >
	<c:param name="subTitle" value="This is subTitle"/>
    </c:import>
   
  • 흐름제어 태그
    if : <c:if test="조건"> </c:if>
    test속성의 값에는 "조건"이 오는데 이 조건문의 결과값이 true 면 처리
     
       <c:if test="true">
         무조건 수행<br>
        </c:if>
    
        <c:if test="${param.name == 'bk'}">
          name 파라미터의 값이 ${param.name}입니다 <br>
        </c:if>
    
        <c:if test="${param.name eq 'bk'}">
          name 파라미터의 값이 ${param.name}입니다 <br>
        </c:if>
    
        <c:if test="${18 < param.age}">
    	 당신의 나이는 18세 이상입니다.
        </c:if>   
       

    choose,when,otherwise : <c:choose>
    <c:when test="조건">
    </c:when>
    <c:otherwise>
    </c:otherwise>
    </c:choose>
    choose 태그는 자바의 switch 문과 if-else 의 혼합한 형태, 다수의 조건문을 하나의 블록에서 수행하고자 할때 사용
    -> switch문과의 차이점은 중간에 빠져 나가지 못한다는 것이다.
    -> when 의 어느 하나에도 실행되지 않을때 otherwise 실행
    -> otherswise 태그가 반드시 있어야 하는것은 아니다.

 
     <c:choose>
       <c:when test="${param.name == 'bk' }">
	<li>당신의 이름은 ${param.name}입니다.
     </c:when>
     <c:when test="${param.age > 18 }">
	<li>당신은 18세 이상입니다.
     </c:when>

     <c:otherwise>
	<li> 당신은 'bk'가 아니고 18세 이상이 아닙니다.
     </c:otherwise>
     </c:choose> 
    

forEach : <c:forEach var="변수" items="아이템" begin="시작값" end="끝값" step="증가값">
</c:forEach>
item 속성에 올수 있는 것들로는 Map,배열,Collection 이 있다.
varStatus는 javax.servlet.jsp.jstl.core.LoopTagStatus 객체 인스턴스변수를 만들며 count라는 프로퍼티가 있어 몇번의 회전인지 알 수있다.

 
       <c:forEach var="i" begin="1" end="9">
	<li>4 *${i} = ${4 *i}
       </c:forEach>

       <h4>int 형 배열</h4>

       <c:forEach var="i" items="${intArray}" begin="2" end="4">
	[${i}]
       </c:forEach>

       <h4>Map</h4>
       <c:forEach var="i" items="${map}">
	  ${i.key} = ${i.value}<br>
       </c:forEach>

       <c:forEach var="member" items="${memberList}" varStatus="memberLoopCount">
	  회원 $(memberLoopCount.count} : ${member} <br>
       </c:forEach>
     

forTokens : <c:forTockens var="token" items="문자열" delins="구분자">
</c:forTockens>
forTokens 태그는 StringTokenizer 와 같은 기능을 제공한다.

 
       <c:forTokens var="token" items="빨강색, 주황색, 노란색, 초록색, 파랑색, 남색, 보라색" delims=",">
     	${token}<br>
       </c:forTokens>
     
  • 숫자 및 날짜 지원 형식
    The JSTL formatting actions allow various data elements in a JSP page, such as numbers,dates and times
    to be formatted and parsed in a locale-sensitive or customized manner.

formatNumber : 숫자 형식을 표현

 
 
      number  : <fmt:formatNumber value="9876543.61" type="number"/>
      currency: <fmt:formatNumber value="9876543.61" type="currency"/>
      percent : <fmt:formatNumber type="percent">9876543.61</fmt:formatNumber>

      pattern=".000"    :<fmt:formatNumber value="9876543.61" pattern=".000" />
      pattern="#,#00.0#":<fmt:formatNumber value="9876543.612345" pattern="#,#00.0#"/>
    

parseNumber : 정해진 패턴을 문자열에서 수치를 파싱해내는 태그
formatDate :날짜 형식을 표현

 
      <jsp:useBean id="now" class="java.util.Date"/>
	
         <c:out value="${now}"/>
           date: <fmt:formatDate value="${now}" type="date"/>
           time: <fmt:formatDate value="${now}" type="time"/>
           both: <fmt:formatDate value="${now}" type="both"/>

           default:<fmt:formatDate value="${now}"
                        type="both" dateStyle="default" timeStyle="default"/>
           short  :<fmt:formatDate value="${now}"
                        type="both" dateStyle="short"   timeStyle="short"  />
           medium :<fmt:formatDate value="${now}"
                        type="both" dateStyle="medium"  timeStyle="medium" />
           long   :<fmt:formatDate value="${now}"
                        type="both" dateStyle="long"    timeStyle="long"   />
           full   :<fmt:formatDate value="${now}"
                        type="both" dateStyle="full"    timeStyle="full"   />

          pattern="yyyy년MM월dd일 HH시mm분ss초"
             <fmt:formatDate value="${now}" type="both"
                             pattern="yyyy년MM월dd일 HH시mm분ss초"/>
            
         <fmt:formatDate value="${now}" pattern="yyyy/MM/dd" />

parseDate :정해진 패턴의 문자열에서 날짜를 파싱해내는 태그
timeZone : <fmt:timeZone value=""/>

setTimeZone : <fmt:timeZone value="" var="" scope=""/>

  • 국제화
    message <fmt:message
    setLocale <fmt:setLocale
    bundle <fmt:bundle
    setBundle <fmt:setBundle
    param <fmt:param
    requestEncoding <fmt:requestEncoding
  • SQL
    <sql:query sql="sqlQuery" var="varName" [scope="{page|request|session|application}"]
    [dataSource="dataSource"] [maxRows="maxRows"] [startRow="startRow"]>
    <sql:param>
    </sql:query>
         <sql:query var="customers" dataSource="${dataSource}">
          SELECT * FROM customers
          WHERE country ='China'
          ORDER BY lastname
         </sql:query>
         
         <table>
          <c:forEach var="row" items="">
             <tr>
               <td><c:out value="${row.lastName}"/></td>
               <td><c:out value="${row.firstName}"/></td>
               <td><c:out value="${row.address}"/></td>
             </tr>
          </c:forEach>
         </table>
       

<sql:update>
<sql:setDataSource>
<sql:param>
<sql:dateParam>

  • XML 코어
    <x:parse>
    <x:out>
    <x:set>
  • 흐름제어
    <x:if>
    <x:choose>
    <x:when>
    <x:otherwise>
    <x:forEach>
  • XML 변환
    <x:transform>
    <x:param>
  • function
    contains
    containsIgnoreCase
    endsWith
    escapeXml
    indexOf
    join
    length
    replace
    split
    startsWith
    substring
    substringAfter
    substringBefore
    toLowerCase
    toUpperCase
    trim
         <c:if test="${fn:contains(name, searchString)}">
         <c:if test="${fn:containsIgnoreCase(name, searchString)}">
         <c:if test="${fn:endsWith(filename, ".txt")}">
         ${fn:escapeXml(param:info)}
         ${fn:indexOf(name, "-")}
         ${fn:join(array, ";")} 
         You have ${fn:length(shoppingCart.products)} in your shopping cart.
         ${fn:replace(text, "-", "•")}
         ${fn:split(customerNames, ";")}
         <c:if test="${fn:startsWith(product.id, "100-")}">
         P.O. Box: ${fn:substring(zip, 6, -1)}
         P.O. Box: ${fn:substringAfter(zip, "-")}
         Zip (without P.O. Box): ${fn:substringBefore(zip, "-")}
         Product name: ${fn.toLowerCase(product.name)}
         Product name: ${fn.UpperCase(product.name)}
         Name: ${fn.trim(name)}
: