리눅스의 PS1은 현재 쉘의 앞부분을 출력할 때 유용하게 사용할 수 있다.


[~] echo :$PS1:

:[\w]\[\033[00m\] :


$ PS1=" \"$PWD\" "

 "/Users/samuel.kim"


"/Users/samuel.kim" PS1="$ "

$


$ PS1="명령 내려주세요 $ "

명령 내려주세요 $

명령 내려주세요 $


$ PS1="\H $ "

google-MacBook-Air-100.local $

google-MacBook-Air-100.local $





리눅스의 PS2는 멀티 커맨드 라인에 사용되는 문자로 사용된다.


$ echo :$PS2:

:> :


$  for x in 10 20 30

> do

> echo $x

> done

10

20

30


$ for x in 10 20 30

 do

 echo $x

 done

10

20

30




자세한 내용은 man bash의 prompting 섹션에 설명되어 있다. 



$ man bash



PROMPTING

       When executing interactively, bash displays the primary prompt  PS1

       when  it  is  ready to read a command, and the secondary prompt PS2

       when it needs more input to complete a command.  Bash allows  these

       prompt strings to be customized by inserting a number of backslash-

       escaped special characters that are decoded as follows:

              \a     an ASCII bell character (07)

              \d     the date in "Weekday Month Date" format  (e.g.,  "Tue

                     May 26")

              \D{format}

                     the format is passed to strftime(3) and the result is

                     inserted into the  prompt  string;  an  empty  format

                     results  in  a  locale-specific  time representation.

                     The braces are required

              \e     an ASCII escape character (033)

              \h     the hostname up to the first `.'

              \H     the hostname

              \j     the number of jobs currently managed by the shell

              \l     the basename of the shell's terminal device name

              \n     newline

              \r     carriage return

              \s     the name of the shell, the basename of $0  (the  por-

                     tion following the final slash)

              \t     the current time in 24-hour HH:MM:SS format

              \T     the current time in 12-hour HH:MM:SS format

              \@     the current time in 12-hour am/pm format

              \A     the current time in 24-hour HH:MM format

              \u     the username of the current user

              \v     the version of bash (e.g., 2.00)




'unix and linux' 카테고리의 다른 글

[shell] 중괄호와 널에 대한 기본 문자열  (0) 2017.02.02
export -p  (0) 2017.01.31
echo 이스케이프 - \c  (0) 2017.01.23
echo 와 >& 팁  (0) 2017.01.19
네트워크 카드의 네트워크 트래픽 확인하기 - iftop  (0) 2017.01.19
Posted by '김용환'
,


echo문을 사용해 yes/no와 같은 답을 얻어야 할 때가 있다.


echo "yes/no" 라고 실행하면 개행 문자가 들어가기 때문에 다음 라인에 yes 또는 no를 입력하게 된다.


이런 불편함을 없애기 위해 \c 이스케이프를 사용할 수 있다.


이스케이프를 쓰려면 유닉스 계열마다 다르게 동작하는 부분이 있다.


$ echo "(yes/no)?"

(yes/no)?

$ echo "(yes/no)?\c"

(yes/no)?\c


맥이나 센트OS에서는 -e를 매개변수로 사용하면 이스케이프 처리된다.


$ echo -e "(yes/no)?\c"

(yes/no)? $



이를 근거로 read 커맨드를 같이 활용하면 다음과 같이 사용가능하다.


$ echo -e "(yes/no)?\c" ; read answer ; echo "$answer"

(yes/no)?yes

yes



이스케이프 문자를 조사하니 다음과 같다.



문자

출력

\b

백스페이스

\c

새로운 라인을 종료하지 않는 라인

\f

폼피드

\n

새로운 라인

\r

캐리지 리턴

\t

탭 문자

\\

백슬래시 문자

\0nnn

해당 문자의 ascii 값은 nnn이고 nnn은 8진수로 1자리부터 3자리를 의미한다


'unix and linux' 카테고리의 다른 글

export -p  (0) 2017.01.31
프롬프팅(prompting) PS1, PS2  (0) 2017.01.31
echo 와 >& 팁  (0) 2017.01.19
네트워크 카드의 네트워크 트래픽 확인하기 - iftop  (0) 2017.01.19
sar를 대체할 수 있는 dstat  (0) 2017.01.19
Posted by '김용환'
,

echo 와 >& 팁

unix and linux 2017. 1. 19. 18:44



echo 와 >& 관련 내용 


<테스트 코드>

$ for i in "once"

  do

    echo "test"

     echo "Error" 1>&2

 done > /dev/null


<결과>

Error message



기본적으로 echo는 echo 출력을 표준 출력(파일 디스크립터(file descriptor) 1)으로 보내는 반면, 파일 설명자 2는 표준 에러이고 기본적으로 파일 리디렉션이나 파이프로 리디렉션되지 않는다. 


따라서 1>&2 표기법은 echo의 "Error" 메시지가 표준 에러로 리디렉션되야 한다는 것을 의미한다. 


Posted by '김용환'
,


트래픽이 어느 ip와 가장 많이 발생하는지 확인할 수 있다.


설치

$ sudo yum install iftop



실행

$ sudo iftop -i eth0





'unix and linux' 카테고리의 다른 글

echo 이스케이프 - \c  (0) 2017.01.23
echo 와 >& 팁  (0) 2017.01.19
sar를 대체할 수 있는 dstat  (0) 2017.01.19
sar 결과에 시간 안나오는 문제  (0) 2017.01.19
[shell] 널 커맨드(null command)  (0) 2017.01.16
Posted by '김용환'
,


시스템 모니터링 툴이 상당히 많지만, 그 중에 sar를 가장 좋아했다.


dstat은 터미널에서 색깔(ansi color)를 입혀 모니터링할 수 있다. sar가 할 수 있는 대부분의 모니터링을 쉽게 할 수 있다. (run queue 모니터링은 dstat에서는 아직 안되는 것 같다.)



과거의 dstat은 옵션이 많았는데, 최신 버전의 dstat은  깔끔하게 사용할 수 있다.



$ dstat -c -d -g -i -l -m -n -p -r -s -t -y





$ dstat -h

Usage: dstat [-afv] [options..] [delay [count]]

Versatile tool for generating system resource statistics


Dstat options:

  -c, --cpu              enable cpu stats

     -C 0,3,total           include cpu0, cpu3 and total

  -d, --disk             enable disk stats

     -D total,hda           include hda and total

  -g, --page             enable page stats

  -i, --int              enable interrupt stats

     -I 5,eth2              include int5 and interrupt used by eth2

  -l, --load             enable load stats

  -m, --mem              enable memory stats

  -n, --net              enable network stats

     -N eth1,total          include eth1 and total

  -p, --proc             enable process stats

  -r, --io               enable io stats (I/O requests completed)

  -s, --swap             enable swap stats

     -S swap1,total         include swap1 and total

  -t, --time             enable time/date output

  -T, --epoch            enable time counter (seconds since epoch)

  -y, --sys              enable system stats


  --aio                  enable aio stats

  --fs, --filesystem     enable fs stats

  --ipc                  enable ipc stats

  --lock                 enable lock stats

  --raw                  enable raw stats

  --socket               enable socket stats

  --tcp                  enable tcp stats

  --udp                  enable udp stats

  --unix                 enable unix stats

  --vm                   enable vm stats


  --plugin-name          enable plugins by plugin name (see manual)

  --list                 list all available plugins


  -a, --all              equals -cdngy (default)

  -f, --full             automatically expand -C, -D, -I, -N and -S lists

  -v, --vmstat           equals -pmgdsc -D total


  --bw, --blackonwhite   change colors for white background terminal

  --float                force float values on screen

  --integer              force integer values on screen

  --nocolor              disable colors (implies --noupdate)

  --noheaders            disable repetitive headers

  --noupdate             disable intermediate updates

  --output file          write CSV output to file


delay is the delay in seconds between each update (default: 1)

count is the number of updates to display before exiting (default: unlimited)



Posted by '김용환'
,

로케일이 깨져서 발생한다.

LC_ALL 또는 LC_TIME의 값을 아무거나 넣고 sar를 실행한다. 

아니면 .bashrc에 export해서 로케일 정보를 저장토록 한다. 

 

$ LC_ALL=x sar  -r -f /var/log/sa/sa03


$ LC_TIME=1 sar  -r -f /var/log/sa/sa03



Posted by '김용환'
,



쉘에 널 커맨드라는 것이 존재한다.  콜론(:)으로 표시되며, 아무것 도 하지 않음을 의미한다. 



e라는 변수가 존재하지 않으면 널 커맨드를 수행하는 예시를 생성한다. 


$ cat xx

#!/bin/sh


if [ -z "$e" ]

then

        :

else

        echo "exit"

        exit 1

fi


echo "xx!"


$ sh xx

xx!

$ echo $?

0




다음에는 잘 동작하는 지 확인하기 위해 -z가 아닌 -n(변수 존재하지 않으면 이라는 뜻을 가짐)을 사용한다. 정상적으로 동작한다. 


$ cat xx

#!/bin/sh


if [ -f "$e" ]

then

        :

else

        echo "exit"

        exit 1

fi


echo "xx!"


$ sh xx

exit

$ echo $?

1




Posted by '김용환'
,



10번째 이상의 매개변수 접근할 때, 조심해야 한다.


간단한 예시이다.


$ cat test.sh

#!/bin/sh


echo $1 $2 $3 $4 $5 $6 $7 $8 $9 $10




다음과 같이 10번째 매개변수를 입력해 본다. $1의 값과 0이 합쳐져 10이 출력된다.


$ ./test.sh 1 2 3 4 5 6 7 8 9 30

1 2 3 4 5 6 7 8 9 10




${n}의 형태로 ${10}을 입력해야 동작한다. 

#!/bin/sh


echo $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10}



테스트를 해보면 잘 동작한다. 

$ ./test.sh 1 2 3 4 5 6 7 8 9 30

1 2 3 4 5 6 7 8 9 30



Posted by '김용환'
,



sed에는 저장 기능이 있다. 특정 패턴에 매칭되면 레지스터에 저장할 수 있다. 


마지막 글자를 레지스터 1에 저장하는 예시는 다음과 같다. 모든 문자(.*) 뒤에 (.)$ 를 얻는다. (나 )는 특수 문자라서 \을 필요로 한다. 


$ echo '123456' |  sed 's/.*\(.\)$/\1/'

6



맨 처음 글자를 레지스터 1에 저장하는 예시는 위 예시를 반대로 하면 된다. 


$ echo '123456' |  sed 's/^\(.\).*/\1/'

1



조금 더 앞으로 나아가 맨 처음 2글자를 뽑아보자. ^\(.\)\(.\)를 .*앞에 추가하고 다음 / 뒤에 \1\2를 추가한다. 

레지스터 1,2에 저장된 내용을 그대로 출력하게 한다.


$ echo '123456' |  sed 's/^\(.\)\(.\).*/\1\2/'

12


그 다음에는 처음에서 두 번째 문자를 출력해보자. 저장된 레지스터 2(\2)를 사용한다.


$ echo '123456' |  sed 's/^\(.\)\(.\).*/\2/'

12



다음은 패턴 매칭에 대한 상세 내용을 본다. 
12과 3이 오면 12를 저장한 내용을 레지스터 1에 저장한다. 그런데, 단 한 번만 출력한다. 


$ echo '1231231' | sed 's/\(12\)3/\1/'

121231



계속 패턴을 적용하려면, 마지막에 g를 추가한다. 


$ echo '1231231' | sed 's/\(12\)3/\1/g'

12121



sed에서 /만 사용해서 처음 만난 a를 A로 처음 바꿀 수 있다. 


$ echo 'aaaaaa' | sed 's/a/A/'

Aaaaaa




다섯 번째 a를 A로도 변경할 수 있다. 


$ echo 'aaaaaa' | sed 's/a/A/5'

aaaaAa




모든 a를 A로 바꾸려면 g를 사용한다. 


$ echo 'aaaaaa' | sed 's/a/A/g'

AAAAAA



이제 조금 익숙해졌다면, 재미있는 패턴 매칭으로 구성할 수 있다. 12와 3으로 이루어진 문자는 12----3,으로 나타내게 한다.



$ echo '123123123' | sed 's/\(12\)\(3\)/\1----\2,/g'

12----3,12----3,12----3,



Posted by '김용환'
,


ntpd를 잘못 설치되어 ntpd가 잘 못 뜰때가 있다. 

(ntp는 클러스터로 동작하는 많은 nosql에서 동기화하는데 중요한 위치를 차지한다. hbase, cassandra 등등이 예로 들 수 있다)


centos 6 기준으로 ntp를 실행한다.


$ sudo service ntpd start

실행 안됨


$ vi /var/log/message


Jan  9 23:45:28 ntpd[12521]: restrict: error in address '::' on line 10. Ignoring...

Jan  9 23:45:28 ntpd[12521]: restrict: error in address '::1' on line 16. Ignoring...

Jan  9 23:45:32 ntpd[12521]: ntpd exiting on signal 15



원인은 장비에 ipv6를 지원하지 않기 때문이다. ipv6을 사용하지 않기 때문에.. 그대로 진행해본다.

(SE와 정확한 원인을 파악하는게 좋다. 사실 ntpd를 다시 삭제하고 설치하는 것을 추천한다.. 하지만 재설치 없이 진행하는 글이 이 블로그의 목적이긴 한다.)



참고로 ntp 데몬이 종료됨을 아래 소스에서 확인할 수 있다. 참고로 signal 15는 SIGTERM이다. 


https://github.com/ntp-project/ntp/blob/master/ntpd/ntpd.c#L1380


static void
finish_safe(
int sig
)
{
const char *sig_desc;
sig_desc = NULL;
#ifdef HAVE_STRSIGNAL
sig_desc = strsignal(sig);
#endif
if (sig_desc == NULL)
sig_desc = "";
msyslog(LOG_NOTICE, "%s exiting on signal %d (%s)", progname,
sig, sig_desc);
/* See Bug 2513 and Bug 2522 re the unlink of PIDFILE */
# ifdef HAVE_DNSREGISTRATION
if (mdns != NULL)
DNSServiceRefDeallocate(mdns);
# endif
peer_cleanup();
exit(0);
}




두 군데를 수정한다. restrict -6 대신 -6을 없애고, restict -6 ::1을 주석 처리한다.


$ vi /etc/ntp.conf

..

#restrict -6 default kod nomodify notrap nopeer noquery

restrict default kod nomodify notrap nopeer noquery


#restrict -6 ::1



다시 데몬을 실행해본다.



$ sudo service ntpd start

실행 안됨


로그를 살펴보면 ntp 사용자가 없기 때문에 에러가 발생한다. (사실, ntpd는 ntp 계정에서 사용하도록 되어 있다.)


$ vi /var/log/message

Cannot find user `ntp'




sudo를 사용해 group과 user 계정을 추가한다. 


$ sudo groupadd -g 87 ntp && sudo useradd -c "Network Time Protocol" -d /var/lib/ntp -u 87 \

        -g ntp -s /bin/false ntp


데몬을 실행하면 잘 동작한다. 


$ sudo service ntpd start

$ ps -ef | grep ntp

ntp       8261     1  0 23:47 ?        00:00:00 ntpd -u ntp:ntp -p /var/run/ntpd.pid -g



정상적으로 실행되는지 ntpq -p를 실행한다. 


$ ntpq -p

     remote           refid      st t when poll reach   delay   offset  jitter

==============================================================================

...



Posted by '김용환'
,