lecture/script 언어

환경변수 및 shell

infra 2021. 11. 9. 18:37

윈도우 서버는 PS1 밖에 없지만, 리눅스는 PS1, PS2의 두 종류 프롬프트가 있다.

bash shell이 default

 

1)Bourne shell 특징은 프롬프트가 $ 이며, root (superuser)로 접속할 시 #

 

2)C shell 같은 경우 프롬프트는 % 이다.

 

bourne shell -> sh

Bourne Again SHell- > bash


C-type shell 변천사

 

C shell -> csh

 


/etc/shell 을 확인하면 가능한 shell들이 나와 있으며,

/etc/passwd에 사용자의 shell이 있다. UID,GID , 홈디렉터리 등등 나타나있다.

 

shell prompt 는 사용자와 상호작용 가능한 입력을 주고 받을 수 있는 명령 대기 표시자로서,

$, # 등이 표시된다.

 

리눅스에선 프롬프트 상태의 PS1= Prompt Statement One을 의미하며, PS2도 있지만, 잘 활용되지 않는다.

 

echo $PS1를 확인하여 출력한 것이며,

 

현재 프롬프트 설정을 볼 수 있으며, \u@\h \W 로 사용자명@호스트명, 현재 마지막 디렉터리 경로만을 나타내지만,

나는 PS1= 을 전체경로로 나타내고 shell prompt도 $로 표시하게 설정해보았다.

 

또한, PS1="\u@\h:\w#" 로 다시 #로만 프롬프트를 변경해보았다.

 

 마지막으로 다시 원래 세팅이었던 디폴트 세팅으로 변경해보았다. PS1=$DEFAULT

아래 표를 통해 기호 및 의미를 파악하면서 활용하면 된다.

 

 

PS1 변수에 사용되는 기호 및 의미

man bash 명령어를 통해 해당 기호 및 설명은 파악 가능하다.

기호 설명
\t
\T 
\@
24시간의 단위로 현재시각을 HH:MM:SS 로 표시
12시간의 단위로 현재시각을 HH:MM:SS 로 표시
12시간의 단위로 현재시각을 오전/오후 로 표시
\d 요일, 월, 일 형식으로 현재 날짜를 나타냄.
\s 현재 사용중인 쉘의 이름을 나타냄 (C쉘=/bin/csh, bash쉘= /bin/bash      /etc/shells 에 사용할수 있는 셸정보 있음)
\w
\W
현재 디렉토리의 전체 절대경로를 모두 표시함
현재 디렉토리의 전체 절대경로명 중 마지막 디렉토리명만을 표시함. 즉 현재디렉토리만 표시함
\u 사용자명을 표시함
\h
\H
서버의 호스트명을 표시함 (www.uzuro.com에서 www 부분)
서버의 도메인명을 표시함 (www.naver.com에서 naver.com 부분)
\# 접속한 순간부터 사용한 명령어의 번호를 1번부터 차례대로 표시함
\! 사용한 명령어의 history 번호를 표시함
\\$ 현재 사용자가 root(uid 가 0 )이면 # 을 표시하고 아니면 $ 를 표시함
\\ '\' 문자 자체를 표시함
\a
\e
ASCII 종소리 문자 (07)
ASCII 의 escape 문자 (033)
\n 개행문자 (줄바꿈)
\v
\V
사용중인 bash 의 버전
사용중인 bash 의 배포, 버전+패치수준으로 버전을 상세히 표시함
\r Carrage retrun
\nnn 8진수 nnn 에 해당하는 문자

쉘변수 기호 의미



출처: https://webdir.tistory.com/105 [WEBDIR]

 

 

printenv (centOS7.4 vs ubuntu 16.04.7)

 

LS_COLORS의 줄은 길고, 색깔에 대한 의미라 해당 내용만 배제하고 환경을 출력해보았다. #printenv

 

 

어떤 유저로 login 할시에 bash 프로그램은 startup files라는 몇몇 설정 script를 읽게 된다.

 

 

 

2)환경 변수

 

process가 컴퓨터에 동작하는 방식에 영향을 미치는 동적인 값들의 모임,

shell에서 정의되고 실행되는 동안 프로그램에 필요한 변수를 나타냄.

 

(1)동작 범위에 따른 환경 변수

 

로컬 환경 변수 현재 접속한 세션에서만 동작하는 환경변수
사용자 환경 변수 특정 사용자에 대해서만 정의된 환경 변수
로컬 terminal session 또는 remote login session을 사용하여 로그인 할 때마다 load 읽어옴.

특정사용자의 홈 디렉터리 경로에서
숨긴 파일인
.bashrc , .bash_profile, .bash_login ,  .bash_logout
.profile (ubuntu ) // .bash_profile(CentOS) 

시스템 전체 환경 변수 해당 시스템에 존재하는 모든 사용자가 사용가능한 환경 변수
시스템 전원이 켜져 있고, 로컬 terminal session 또는 remote login session을 사용하여 로그인 할 때마다 load 읽어옴

/etc/environment
/etc/profile
/etc/profile.d/
/etc/bash.bashrc



 

(2)환경 변수 구성파일

 

 

 

파일명 또는 경로 추가 타 경로 및 설명 설명
.bashrc    해당 파일은 전역 설정 파일인 /etc/bashrc 가 먼저 수행된 다음에 .bashrc가 수행된다.

/etc/bashrc :
전역설정 파일,
모든 사용자에게 영향 줌


~/.bashrc :
  오직 bash를 실행하는 사용자에게만 영향을 줌.

<그림1> 참조: 사용자 root, test1,test2의 ~/.bashrc 에 담겨진 내용

특정 사용자가 새로운 local session을 생성 할 때 마다 load되는 파일


.bash_profile /etc/profile에서 전역설정 파일에서 먼저 수행된다음 해당 .bash_profile이 수행된다.

해당 파일이 존재하지 않다면, .bash_login 또는 .profile 파일을 검색하면 된다.

이또한 .bashrc처럼 오직 .bash_profile을 실행하는 사용자에게만 영향을 준다.

<그림2> 참조
특정 사용자가 원격 로그인(remote login) file을 의미하며, 이파일에 있는 환경 변수는 사용자가 원격 로그인 세션이 이루어질 시에 호출된다.
/etc/bashrc   (ubuntu /etc/bash.bashrc) <표1> 참조 시스템 전체의 bashrc파일
-모든 사용자가 local terminal session을 열 때마다 load된다.
-이 파일에서 만든 환경 변수는 모든 사용자가 접근 가능하나, local terminal session에서만 가능하다.
/etc/profile

<표2> 참조
-시스템 전체의 profile의 파일
-모든 사용자가 remote login session이 이루어질 시 호출된다.
-이 파일에서 만든 환경 변수는 모든 사용자가 접근 가능하나, remote login session에서만 가능하다.
/etc/environment 전반적인 시스템을 제어하는 파일
필요한 환경변수를 작성하거나 편집 및 제거가 가능하다.
해당 파일에서 수정한 환경 변수는 로컬 및 원격으로 접속한 모든 사용자가 접근 가능하다.

<그림1,2> 더보기 클릭하면 펼쳐짐

더보기

&lt;그림1&gt; 사용자 root, test1, test2 의 home directory의 .bashrc (경로 ~/.bashrc)

 

 

&lt;그림2&gt;사용자 root, test1,test2 의 home directory 구조(~/etc/.bash_profile)

 

 

<표1,2 > 더보기 클릭하면 펼쳐짐

더보기

 

CentOS7.4 /etc/bashrc 파일 내용 ubuntu 16.04 의 /etc/bash.bashrc 파일 내용
if [ "$PS1" ]; then
  if [ -z "$PROMPT_COMMAND" ]; then
    case $TERM in
    xterm*|vte*)
      if [ -e /etc/sysconfig/bash-prompt-xterm ]; then
          PROMPT_COMMAND=/etc/sysconfig/bash-prompt-xterm
      elif [ "${VTE_VERSION:-0}" -ge 3405 ]; then
          PROMPT_COMMAND="__vte_prompt_command"
      else
          PROMPT_COMMAND='printf "\033]0;%s@%s:%s\007" "${USER}" "${HOSTNAME%%.*}" "${PWD/#$HOME/~}"'
      fi
      ;;
    screen*)
      if [ -e /etc/sysconfig/bash-prompt-screen ]; then
          PROMPT_COMMAND=/etc/sysconfig/bash-prompt-screen
      else
          PROMPT_COMMAND='printf "\033k%s@%s:%s\033\\" "${USER}" "${HOSTNAME%%.*}" "${PWD/#$HOME/~}"'
      fi
      ;;
    *)
      [ -e /etc/sysconfig/bash-prompt-default ] && PROMPT_COMMAND=/etc/sysconfig/bash-prompt-default
      ;;
    esac
  fi
  # Turn on parallel history
  shopt -s histappend
  history -a
  # Turn on checkwinsize
  shopt -s checkwinsize
  [ "$PS1" = "\\s-\\v\\\$ " ] && PS1="[\u@\h \W]\\$ "
  # You might want to have e.g. tty in prompt (e.g. more virtual machines)
  # and console windows
  # If you want to do so, just add e.g.
  # if [ "$PS1" ]; then
  #   PS1="[\u@\h:\l \W]\\$ "
  # fi
  # to your custom modification shell script in /etc/profile.d/ directory
fi

if ! shopt -q login_shell ; then # We're not a login shell
    # Need to redefine pathmunge, it get's undefined at the end of /etc/profile
    pathmunge () {
        case ":${PATH}:" in
            *:"$1":*)
                ;;
            *)
                if [ "$2" = "after" ] ; then
                    PATH=$PATH:$1
                else
                    PATH=$1:$PATH
                fi
        esac
    }

    # By default, we want umask to get set. This sets it for non-login shell.
    # Current threshold for system reserved uid/gids is 200
    # You could check uidgid reservation validity in
    # /usr/share/doc/setup-*/uidgid file
    if [ $UID -gt 199 ] && [ "`/usr/bin/id -gn`" = "`/usr/bin/id -un`" ]; then
       umask 002
    else
       umask 022
    fi

    SHELL=/bin/bash
    # Only display echos from profile.d scripts if we are no login shell
    # and interactive - otherwise just process them to set envvars
    for i in /etc/profile.d/*.sh; do
        if [ -r "$i" ]; then
            if [ "$PS1" ]; then
                . "$i"
            else
                . "$i" >/dev/null
            fi
        fi
    done

    unset i
    unset -f pathmunge
fi
# vim:ts=4:sw=4
# If not running interactively, don't do anything
[ -z "$PS1" ] && return

# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

# set a fancy prompt (non-color, overwrite the one in /etc/profile)
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '

# Commented out, don't overwrite xterm -T "title" -n "icontitle" by default.
# If this is an xterm set the title to user@host:dir
#case "$TERM" in
#xterm*|rxvt*)
#    PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME}: ${PWD}\007"'
#    ;;
#*)
#    ;;
#esac

# enable bash completion in interactive shells
#if ! shopt -oq posix; then
#  if [ -f /usr/share/bash-completion/bash_completion ]; then
#    . /usr/share/bash-completion/bash_completion
#  elif [ -f /etc/bash_completion ]; then
#    . /etc/bash_completion
#  fi
#fi

# sudo hint
if [ ! -e "$HOME/.sudo_as_admin_successful" ] && [ ! -e "$HOME/.hushlogin" ] ; then
    case " $(groups) " in *\ admin\ *|*\ sudo\ *)
    if [ -x /usr/bin/sudo ]; then
        cat <<-EOF
        To run a command as administrator (user "root"), use "sudo <command>".
        See "man sudo_root" for details.

        EOF
    fi
    esac
fi

# if the command-not-found package is installed, use it
if [ -x /usr/lib/command-not-found -o -x /usr/share/command-not-found/command-not-found ]; then
        function command_not_found_handle {
                # check because c-n-f could've been removed in the meantime
                if [ -x /usr/lib/command-not-found ]; then
                   /usr/lib/command-not-found -- "$1"
                   return $?
                elif [ -x /usr/share/command-not-found/command-not-found ]; then
                   /usr/share/command-not-found/command-not-found -- "$1"
                   return $?
                else
                   printf "%s: command not found\n" "$1" >&2
                   return 127
                fi
        }
fi

<표1>

 

CentOS 7.4 /etc/profile ubuntu 16.04 /etc/profile
pathmunge () {
    case ":${PATH}:" in
        *:"$1":*)
            ;;
        *)
            if [ "$2" = "after" ] ; then
                PATH=$PATH:$1
            else
                PATH=$1:$PATH
            fi
    esac
}


if [ -x /usr/bin/id ]; then
    if [ -z "$EUID" ]; then
        # ksh workaround
        EUID=`/usr/bin/id -u`
        UID=`/usr/bin/id -ru`
    fi
    USER="`/usr/bin/id -un`"
    LOGNAME=$USER
    MAIL="/var/spool/mail/$USER"
fi

# Path manipulation
if [ "$EUID" = "0" ]; then
    pathmunge /usr/sbin
    pathmunge /usr/local/sbin
else
    pathmunge /usr/local/sbin after
    pathmunge /usr/sbin after
fi

HOSTNAME=`/usr/bin/hostname 2>/dev/null`
HISTSIZE=1000
if [ "$HISTCONTROL" = "ignorespace" ] ; then
    export HISTCONTROL=ignoreboth
else
    export HISTCONTROL=ignoredups
fi

export PATH USER LOGNAME MAIL HOSTNAME HISTSIZE HISTCONTROL

# By default, we want umask to get set. This sets it for login shell
# Current threshold for system reserved uid/gids is 200
# You could check uidgid reservation validity in
# /usr/share/doc/setup-*/uidgid file
if [ $UID -gt 199 ] && [ "`/usr/bin/id -gn`" = "`/usr/bin/id -un`" ]; then
    umask 002
else
    umask 022
fi

for i in /etc/profile.d/*.sh ; do
    if [ -r "$i" ]; then
        if [ "${-#*i}" != "$-" ]; then
            . "$i"
        else
            . "$i" >/dev/null
        fi
    fi
done

unset i
unset -f pathmunge
export TMOUT=1800
if [ "$PS1" ]; then
  if [ "$BASH" ] && [ "$BASH" != "/bin/sh" ]; then
    # The file bash.bashrc already sets the default PS1.
    # PS1='\h:\w\$ '
    if [ -f /etc/bash.bashrc ]; then
      . /etc/bash.bashrc
    fi
  else
    if [ "`id -u`" -eq 0 ]; then
      PS1='# '
    else
      PS1='$ '
    fi
  fi
fi

if [ -d /etc/profile.d ]; then
  for i in /etc/profile.d/*.sh; do
    if [ -r $i ]; then
      . $i
    fi
  done
  unset i
fi
/etc/environment (CentOS vs ubuntu ) 및 echo $PATH
[root@centos7 ~]# cat /etc/environment


[root@centos7 ~]# echo $PATH
/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
root@ubuntu16:~# cat /etc/environment
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"


root@ubuntu16:~# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

<표2>

 

 

 

 

 

 

 

출처 :

 

1)

https://webterror.net/?p=1791 

 

리눅스 환경변수의 설명 – WEBTERROR.net

1. bash에서의 쉘변수와 환경변수(1) 쉘변수 1) 개요: 말 그대로 특정한 쉘 즉 bash에서만 적용되는 변수를 말한다. 2) 특징 ㄱ. 지정하는 방법은 ‘변수명=값’ 형태로 지정하면 된다. 예) [posein@www pos

webterror.net

 

2)

https://blog.naver.com/PostView.nhn?isHttpsRedirect=true&blogId=koromoon&logNo=220793570727 

 

리눅스 환경 변수

참고 사이트 : http://www.tecmint.com/set-unset-environment-variables-in-linux/ http://originalchoi.t...

blog.naver.com