서버/Linux II 2016. 2. 26. 17:50

Linux II - 09. Linux Shell

 

 

 

login as: root
root@192.168.1.7's password:
Last login: Tue Feb 23 15:17:53 2016 from 192.168.1.1
[root@CentOS2 /root]#

 

 

 

 

1. Shell

 

Shell은 리눅스 사용자와 커널 사이에서 동작하는 인터페이스 역할을 담당하는 프로그램을 의미한다. 리눅스 사용자가 실행한 명령어를 해석하여 커널에게 전달하는 역할을 수행하기 때문에 명령어 해석기라고 생각해도 된다. 다음 정보 확인은 커널을 확인한 것이다. 이때, Shell은 명령어가 입력되면, 커널에게 명령을 해석하여 전달하는 역할을 수행한다.

 

[root@CentOS2 /root]# ls /boot/vmlinuz-2.6.32-504.el6.x86_64
/boot/vmlinuz-2.6.32-504.el6.x86_64               

[root@CentOS2 /root]# ls -l /boot/vmlinuz-2.6.32-504.el6.x86_64
-rwxr-xr-x. 1 root root 4152336 2014-10-15 13:54 /boot/vmlinuz-2.6.32-504.el6.x86_64

 

Shell은 다음과 같은 기능을 수행한다.

 

 - 입력을 읽고, 해당 명령행을 분석하여 커널에게 전달한다.

 

[root@CentOS2 /root]# ls
anaconda-ks.cfg  install.log.syslog  sdb2  다운로드  바탕화면  사진  템플릿
install.log      sdb1                공개  문서      비디오    음악

 

 - 특수 문자를 분석하여 커널에게 전달한다.


[root@CentOS2 /root]# echo *
anaconda-ks.cfg install.log install.log.syslog sdb1 sdb2 공개 다운로드 문서 바탕화면 비디오 사진 음악 템플릿

 

 - 파이프, 리디렉션, 백그라운드 프로세스를 처리한다.

 

[root@CentOS2 /root]# ls | wc -l
13

 

 

 

2. Shell 유형

 

 

[root@CentOS2 /root]# chsh -l
/bin/sh
/bin/bash
/sbin/nologin
/bin/dash
/bin/tcsh
/bin/csh

 

 - 현재 ksh를 지원되지 않는다. 'yum' 명령어를 이용하여 ksh 쉘을 설치하도록 한다.

 

[root@CentOS2 /root]# yum install ksh

[root@CentOS2 /root]# chsh -l
/bin/sh
/bin/bash
/sbin/nologin
/bin/dash
/bin/tcsh
/bin/csh
/bin/ksh

 

 - Shell은 /bin 디렉토리에 저장되어 있다.

 

[root@CentOS2 /root]# ls /bin/*sh
/bin/bash  /bin/csh  /bin/dash  /bin/ksh  /bin/sh  /bin/tcsh

 

 

쉘 유형

내용 

 bash

 - 기본적으로 사용하는 Shell

 - 편리한 사용자 인터페이스 제공 및 확장된 문법제공

 - 명령행 편집기 기능 제공

 sh

 - Steven Bourne이 개발한 최초 대중화된 유닉스 Shell

 - 명령행 편집 기능이 없음

 csh

 - Billy Joy이 개발한 Shell이며, 프로그래머들이 선호함

 - 리눅스 기본 Shell인 본쉘하고는 호환이 안됨

 ksh

 - David Korn이 개발한 Shell

 - 사용자 인터페이스가 좋으며, 본쉘과도 호환됨

 - 명령행 편집기 기능 제공

 

 

Ex1) ksh 쉘 (bash 쉘과 문법이 호환 가능)

 

[root@CentOS2 /root]# ssh -l user1 localhost
user1@localhost's password: centos
Last login: Mon Feb 29 18:41:07 2016 from localhost
[user1@CentOS2 /home/user1]$


[user1@CentOS2 /home/user1]$ chsh
Changing shell for user1.
암호: centos
New shell [/bin/bash]: /bin/ksh
Shell changed.
[user1@CentOS2 /home/user1]$


[user1@CentOS2 /home/user1]$ ps
  PID TTY          TIME CMD
 5392 pts/3    00:00:00 bash
 5425 pts/3    00:00:00 ps

[user1@CentOS2 /home/user1]$ cat /etc/passwd | tail -2
user1:x:500:500::/home/user1:/bin/ksh
user2:x:501:501::/home/user2:/bin/bash


[user1@CentOS2 /home/user1]$ exit
logout
Connection to localhost closed.
[root@CentOS2 /root]#


[root@CentOS2 /root]# ssh -l user1 localhost
user1@localhost's password: centos
Last login: Mon Feb 29 18:41:21 2016 from localhost
$
$ ps
  PID TTY          TIME CMD
 5441 pts/3    00:00:00 ksh
 5452 pts/3    00:00:00 ps
$
$ a=100
$ b=200
$ echo $PATH
/usr/lib64/qt-3.3/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin
$
$ ls /etc/passwds          pass까지 입력하고 Tab 실시(Tab 2번 실시)
1) passwd
2) passwd-
3) passwd.OLD
$

$ ls /etc/passwd           's' 문자를 삭제하려면 , x를 눌러야 함
/etc/passwd
$
$ chsh
Changing shell for user1.
암호: centos
New shell [/bin/ksh]: /bin/bash
Shell changed.
$ exit
Connection to localhost closed.
[root@CentOS2 /root]#
[root@CentOS2 /root]# ssh -l user1 localhost
user1@localhost's password: centos
Last login: Mon Feb 29 18:41:50 2016 from localhost
[user1@CentOS2 /home/user1]$


 

 

Ex2) csh 쉘 (다른 쉘하고 문법이 호환이 안됨)


[user1@CentOS2 /home/user1]$ csh
[user1@CentOS2 ~]$
[user1@CentOS2 ~]$ ps
  PID TTY          TIME CMD
 5279 pts/1    00:00:00 bash
26746 pts/1    00:00:00 csh
26755 pts/1    00:00:00 ps

[user1@CentOS2 ~]$ set a = 100
[user1@CentOS2 ~]$

[user1@CentOS2 ~]$ exit
exit
[user1@CentOS2 /home/user1]$
[user1@CentOS2 /home/user1]$ ps
  PID TTY          TIME CMD
 5279 pts/1    00:00:00 bash
26773 pts/1    00:00:00 ps

[user1@CentOS2 /home/user1]$ exit
logout
Connection to localhost closed.
[root@CentOS2 /root]#

 

 

 

Ex3) Bash 쉘 (리눅스 기본 쉘로 동작함)

 

[root@CentOS2 /root]# ps
  PID TTY          TIME CMD
 2885 pts/0    00:00:00 bash
26780 pts/0    00:00:00 ps

[root@CentOS2 /root]# useradd -D
GROUP=100
HOME=/home
INACTIVE=-1
EXPIRE=
SHELL=/bin/bash
SKEL=/etc/skel
CREATE_MAIL_SPOOL=yes

[root@CentOS2 /root]# cd /etc/init.d               서버와 관련된 파일 디렉토리 (대부분 Bash 쉘로 생성한 파일들이다.)
[root@CentOS2 /etc/init.d]# ls
NetworkManager    haldaemon      network      single
abrt-ccpp         halt           nfs          smartd
abrt-oops         hsqldb         nfslock      smb
abrtd             htcacheclean   nmb          snmpd
acpid             httpd          ntpd         snmptrapd
atd               ip6tables      ntpdate      spamassassin
auditd            ipa            oddjobd      spice-vdagentd
autofs            ipa_memcached  pki-cad      sshd
blk-availability  iptables       portreserve  sssd
bluetooth         irqbalance     postfix      svnserve
certmonger        kadmin         psacct       sysstat
cgconfig          kdump          quota_nld    tgtd
cgred             killall        rdisc        tomcat6
cpuspeed          kprop          restorecond  udev-post
crond             krb5kdc        rngd         vmware-tools
cups              lvm2-lvmetad   rpcbind      vmware-tools-thinprint
dirsrv            lvm2-monitor   rpcgssd      vsftpd
dirsrv-snmp       mdmonitor      rpcidmapd    wdaemon
dnsmasq           memcached      rpcsvcgssd   winbind
dovecot           messagebus     rsyslog      wpa_supplicant
firstboot         netconsole     sandbox      xinetd
functions         netfs          saslauthd    ypbind


[root@CentOS2 /etc/init.d]# file *sshd
sshd: Bourne-Again shell script text executable

 

[root@CentOS2 /etc/init.d]# cat sshd        Bash 쉘로 작성된 내용 확인

[root@CentOS2 /etc/init.d]# cd
[root@CentOS2 /root]#

 

 

 

 

3. Bash Shell 관련 파일

 

[root@CentOS2 /root]# ls .bash*
.bash_history  .bash_logout  .bash_profile  .bashrc

 

 

 1) 로그인할때 Shell이 Bash Shell이면 다음과 같은 순서대로 해당 파일들이 실행된다.

 

/etc/profile -> $HOME/.bash_profile -> $HOME/.bashrc -> /etc/bashrc

 

 

 - /etc/profile : 시스템을 사용하는데 필요한 환경 변수들이 들어가 있다. 다음 정보 확인을 통하여 확인할 수 있다.

 

[root@CentOS2 /root]# vi /etc/profile          (# cat /etc/profile)

 

 

 - $HOME/.bash_profile : 계정들이 필요한 환경 변수들이 들어가 있다. 다음 정보 확인을 통하여 확인할 수 있다.


[root@CentOS2 /root]# ls .bash*
.bash_history  .bash_logout  .bash_profile  .bashrc

[root@CentOS2 /root]# vi .bash_profile      (# cat .bash_profile)

 

 

 - $HOME/.bashrc : 명령어를 자동으로 사용하기 위한 명령어가 들어가 있다. 다음 정보 확인을 통하여 확인할 수 있다.

 

[root@CentOS2 /root]# ls .bash*
.bash_history  .bash_logout  .bash_profile  .bashrc

 

[root@CentOS2 /root]# vi .bashrc            (# cat .bashrc)

 

 

 

 2) 로그인 Shell이 종료될 경우, 다음과 같은 파일이 실행된다.

 

$HOME/.bash_logout 실행 -> 'bash shell 명령어 사용 기록들' -> $HOME/.bash_history 파일에 저장

 

 

 - $HOME/.bash_logout : 로그 아웃할때 실행되는 파일이다. 로그 아웃 관련 배너를 설정할 수 있다.

 

[root@CentOS2 /root]# cat .bash_logout
# ~/.bash_logout

 

 

 - $HOME/.bash_history : 로그 아웃하면, 기존에 했던 모든 명령어들을 저장한다.

 

[root@CentOS2 /root]# cat .bash_history

 

 

 

Ex1) '.bash_profile' -> '.bashrc' 실행 확인

 

[root@CentOS2 /root]# su - user1
[user1@CentOS2 /home/user1]$
[user1@CentOS2 /home/user1]$ vi .bash_profile

 

echo ".bash_profile started"    <- 추가
# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
        . ~/.bashrc
fi

# User specific environment and startup programs

PATH=$PATH:$HOME/bin

export PATH

 

: wq!

 

 

[user1@CentOS2 /home/user1]$ vi .bashrc

echo ".bashrc started"   <- 추가
# .bashrc

# Source global definitions
if [ -f /etc/bashrc ]; then
        . /etc/bashrc
fi
PS1="[\u@\h \$PWD]$ "
export PS1
# User specific aliases and functions

: wq!

 

 

[user1@CentOS2 /home/user1]$ ssh -l user1 localhost
user1@localhost's password: centos
Last login: Wed Mar  2 17:15:10 2016 from localhost
.bash_profile started
.bashrc started
[user1@CentOS2 /home/user1]$
[user1@CentOS2 /home/user1]$ exit

logout

Connection to localhost closed.

 

[user1@CentOS2 /home/user1]$
[user1@CentOS2 /home/user1]$ exit
logout


[root@CentOS2 /root]#



 

 

Ex2) user2 접속시 배너 설정


[root@CentOS2 /root]# su - user2
[user2@CentOS2 /home/user2]$


[user2@CentOS2 /home/user2]$ vi banner.txt

 

배너(소).txt

 

                 _---------.
             .' #######   ;."
  .---,.    ;@             @@`;   .---,..
." @@@@@'.,'@@            @@@@@',.'@@@@ ".
'-.@@@@@@@@@@@@@          @@@@@@@@@@@@@ @;
   `.@@@@@@@@@@@@        @@@@@@@@@@@@@@ .'
     "--'.@@@  -.@        @ ,'-   .'--"
          ".@' ; @       @ `.  ;'
            |@@@@ @@@     @    .
             ' @@@ @@   @@    ,
              `.@@@@    @@   .
                ',@@     @   ;
                 (   3 C    )
                 ;@'. __*__,."
                  '(.,...."/

 


 : wq!

 

 

[user2@CentOS2 /home/user2]$ vi .bashrc

# .bashrc

# Source global definitions
if [ -f /etc/bashrc ]; then
        . /etc/bashrc
fi
PS1="[\u@\h \$PWD]$ "
export PS1
# User specific aliases and functions
cat banner.txt    <- 추가

: wq!

 

 

[user2@CentOS2 /home/user2]$ ssh -l user2 localhost
user2@localhost's password: centos
Last login: Wed Mar  2 17:34:13 2016 from localhost
                 _---------.
             .' #######   ;."
  .---,.    ;@             @@`;   .---,..
." @@@@@'.,'@@            @@@@@',.'@@@@ ".
'-.@@@@@@@@@@@@@          @@@@@@@@@@@@@ @;
   `.@@@@@@@@@@@@        @@@@@@@@@@@@@@ .'
     "--'.@@@  -.@        @ ,'-   .'--"
          ".@' ; @       @ `.  ;'
            |@@@@ @@@     @    .
             ' @@@ @@   @@    ,
              `.@@@@    @@   .
                ',@@     @   ;
                 (   3 C    )
                 ;@'. __*__,."
                  '(.,...."/

 


[user2@CentOS2 /home/user2]$ exit
logout
Connection to localhost closed.

[user2@CentOS2 /home/user2]$ exit
logout


[root@CentOS2 /root]#

 

 

 

4. Shell 변수

 

변수는 파일로 동작하는 것이 아니라, 메모리에 올라가서 동작한다.

 

 

 1) 사용자 정의 변수

 

  - 사용자가 필요할때, 임시로 만들어서 사용하는 변수를 의미한다. 주로 소문자를 사용하며, 현재 쉘에서만 사용할 수 있다.

 

[root@CentOS2 /root]# mkdir test
[root@CentOS2 /root]# cd test
[root@CentOS2 /root/test]#

[root@CentOS2 /root/test]# a=100        ('='는 'a에 100을 대입한다'라는 의미이다.)
[root@CentOS2 /root/test]# b=200
[root@CentOS2 /root/test]# c=hello
[root@CentOS2 /root/test]# d="hello linux"

[root@CentOS2 /root/test]#
[root@CentOS2 /root/test]# echo $a $b
100 200


[root@CentOS2 /root/test]# echo $c
hello

[root@CentOS2 /root/test]# echo $d
hello linux

 

 - 사용자 변수는 로그 아웃하면, 메모리에 올라가 있기 때문에 자동으로 삭제된다. 만약, 수동으로 삭제할 경우 다음과 같다.

 

[root@CentOS2 /root/test]# unset a b c d

[root@CentOS2 /root/test]# echo $a $b $c $d

 

 

Ex) 사용자 정의 변수

 

[root@CentOS2 /root/test]# cat /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
HWADDR=00:0C:29:5A:3C:B4
TYPE=Ethernet
UUID=8b2a8658-d6ed-48c5-9b2a-d6203d29149f
ONBOOT=yes
NM_CONTROLLED=yes
BOOTPROTO=dhcp

[root@CentOS2 /root/test]# nic=/etc/sysconfig/network-scripts/ifcfg-eth0

[root@CentOS2 /root/test]# echo $nic
/etc/sysconfig/network-scripts/ifcfg-eth0

[root@CentOS2 /root/test]# cat $nic
DEVICE=eth0
HWADDR=00:0C:29:5A:3C:B4
TYPE=Ethernet
UUID=8b2a8658-d6ed-48c5-9b2a-d6203d29149f
ONBOOT=yes
NM_CONTROLLED=yes
BOOTPROTO=dhcp

 

 

 

 2) 환경 변수

 

  - 자주 사용하는 사용자 정의 변수를 환경 변수에 저장하면, 자식 쉘에도 적용된다.

  - 또한, 환경 변수를 각 계정 '.bash_profile'에 설정하면 로그아웃을 실시해도 다음 로그인때 사용할 수 있다.

  - 주로 대문자를 사용하며, 로그인하기 이전에 미리 정의되어 있어야 한다.

  - 'env' 명령어를 이용하여 확인할 수 있다.  ('set' 명령어는 모든 변수를 확인할 수 있다.)

 

[root@CentOS2 /root/test]# env

[root@CentOS2 /root/test]# echo $PATH
/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin

 

Ex) 환경 변수

 

[root@CentOS2 /root/test]# a=100
[root@CentOS2 /root/test]# b=200
[root@CentOS2 /root/test]# export a
[root@CentOS2 /root/test]# export b
[root@CentOS2 /root/test]# export nic

[root@CentOS2 /root/test]# env

 

 

[root@CentOS2 /root/test]# bash


[root@CentOS2 /root/test]# echo $a
100


[root@CentOS2 /root/test]# echo $b
200


[root@CentOS2 /root/test]# echo $nic
/etc/sysconfig/network-scripts/ifcfg-eth0


[root@CentOS2 /root/test]#
[root@CentOS2 /root/test]# exit
exit
[root@CentOS2 /root/test]# cd
[root@CentOS2 /root]#

 

 

 - 다음과 같이 '.bash_profile'에 환경 변수를 추가하면, 해당 계정이 로그인될때 자동으로 적용된다.

 

[root@CentOS2 /root]# vi .bash_profile

  1 # .bash_profile
  2
  3 # Get the aliases and functions
  4 if [ -f ~/.bashrc ]; then
  5     . ~/.bashrc
  6 fi
  7
  8 # User specific environment and startup programs
  9
 10 PATH=$PATH:$HOME/bin
 11 NIC=/etc/sysconfig/network-scripts/ifcfg-eth0     <- 추가
 12 export PATH
 

: wq!

 

 

 

 3) Shell 내장 변수

 

  - Shell에 내장되어 있는 변수이며, 인수를 받아서 처리하기 위해서 주로 사용한다.

  - 변수명은 직접 설정할 수 없는 특수 문자 또는 숫자로 되어있다.

 

[root@CentOS2 /root]# cd test
[root@CentOS2 /root/test]#

[root@CentOS2 /root/test]# vi var.sh

  1 echo "1: $0 $1 $2 $5"
  2 echo "2: $#"
  3 echo "3: $*"
  4 echo "4: $@"
  5 echo "5: $?"
  6 echo "6: $$"

: wq!

 

 

[root@CentOS2 /root/test]# cat var.sh
echo "1: $0 $1 $2 $5"
echo "2: $#"
echo "3: $*"
echo "4: $@"
echo "5: $?"
echo "6: $$"

[root@CentOS2 /root/test]# ./var.sh
-bash: ./var.sh: 허가 거부


[root@CentOS2 /root/test]# ls -l var.sh
-rw-r--r--. 1 root root 88 2016-03-03 16:37 var.sh

[root@CentOS2 /root/test]# chmod u+x var.sh

[root@CentOS2 /root/test]# ls -l var.sh
-rwxr--r--. 1 root root 88 2016-03-03 16:37 var.sh

[root@CentOS2 /root/test]# ./var.sh
1: ./var.sh
2: 0
3:
4:
5: 0
6: 2862

 

[root@CentOS2 /root/test]# cat var.sh
echo "1: $0 $1 $2 $5"  (0,1,2,5 인수 출력 변수)
echo "2: $#"    (인수의 개수 출력 변수)
echo "3: $*"    (모든 인수 출력 변수)
echo "4: $@"   (모든 인수 출력 변수)
echo "5: $?"    (리턴값 변수, '0'이면 정상)
echo "6: $$"    (프로세스 ID가 저장되는 변수)

[root@CentOS2 /root/test]# ./var.sh 100 hello 200
1: ./var.sh 100 hello
2: 3
3: 100 hello 200
4: 100 hello 200
5: 0
6: 2872

 

 

[참고] '?' 변수 (리턴값 저장 변수)

 

 - 명령어가 정상적으로 실행되고 성립되면, '0'값이 리턴된다.

 

[root@CentOS2 /root/test]# ls
var.sh

[root@CentOS2 /root/test]# echo $?
0

 

 

 - 만약, 명령어가 잘못됬거나, 없는 파일을 확인할 경우, 리턴값은 '0'이 아니다.


[root@CentOS2 /root/test]# cd..
-bash: cd..: command not found

[root@CentOS2 /root/test]# echo $?
127      <- 명령어를 잘못 사용한 경우


 

[root@CentOS2 /root/test]# ls a.txt
ls: cannot access a.txt: 그런 파일이나 디렉터리가 없습니다


[root@CentOS2 /root/test]# echo $?
2         <- 인수를 잘못 대입할 경우

 

 

 - 만약, 에러는 없지만, 해당 내용이 없을 경우, 리턴값은 '1'이 나온다.


[root@CentOS2 /root/test]# grep hacker /etc/passwd

[root@CentOS2 /root/test]# echo $?
1

 

[참고] 사칙 연산

 

[root@CentOS2 /root/test]# expr 100 + 200
300

[root@CentOS2 /root/test]# expr 100 - 200
-100

[root@CentOS2 /root/test]# expr 100 / 200
0     <- 0 보다 작으면 0으로 나옴

[root@CentOS2 /root/test]# expr 100 \* 200
20000

[root@CentOS2 /root/test]# a=100
[root@CentOS2 /root/test]# b=200
[root@CentOS2 /root/test]# c=`expr $a + $b`


[root@CentOS2 /root/test]# echo $c
300

[root@CentOS2 /root/test]# let a=10*2
[root@CentOS2 /root/test]# echo $a
20

 

 

 

Ex) Shell 내장 변수

 

[root@CentOS2 /root/test]# ./test.sh 5 10
5 * 10 = 50


[root@CentOS2 /root/test]# vi test.sh

  1 number1=$1
  2 number2=$2
  3 #let result=number1*number2  <- 밑에 설정과 동일한 내용이므로 주석 처리 실시
  4 result=`expr $number1 \* $number2`
  5 echo "$number1 * $number2 = $result"

 

: wq!

 


[root@CentOS2 /root/test]# ./test.sh
-bash: ./test.sh: 허가 거부


[root@CentOS2 /root/test]# chmod u+x test.sh

[root@CentOS2 /root/test]# ./test.sh 5 10
5 * 10 = 50


[root@CentOS2 /root/test]# ./test.sh 6 10
6 * 10 = 60

 

 

 - '/etc/init.d'에 있는 파일들은 대부분 스크립트 파일이다. 이때, Shell 내장 변수를 이용하여 스크립트가 작성되어 있다.

 

[root@CentOS2 /root/test]# cd /etc/init.d
[root@CentOS2 /etc/init.d]# file *

[root@CentOS2 /etc/init.d]# vi vsftpd

 

 

 

 

 

 

 

 

 - 설정 초기화


[root@CentOS2 /etc/init.d]# cd
[root@CentOS2 /root]#

 

[root@CentOS2 /root]# rm -rf test

'서버 > Linux II' 카테고리의 다른 글

Linux II - 11. 백업 & 복구  (0) 2016.03.04
Linux II - 10. Linux 부팅 과정  (0) 2016.03.03
Linux II - 08. 디스크 Quota  (0) 2016.02.23
Linux II - 07. RAID 관리  (0) 2016.02.23
Linux II - 06. LVM (Logical Volume Manager)  (0) 2016.02.19
Posted by 김정우 강사(카카오톡 : kim10322)
,


Q