Skip to content
TUWLAB.com
모든 게시물에 대하여 '링크'
방식의 퍼가기만 허용합니다.
한양대학교 전자통신컴퓨터공학부
바라미
  • 35
  • 2595299
DNS Powered by DNSEver.com
Linux

[Ubuntu] Bashrc Shell Prompt 커스터마이징 (.bashrc PS1)

Posted 2013. 07. 14 Updated 2014. 04. 24 Views 22855 Replies 0

Ubuntu의 터미널이나 SSH 접속시 표시되는 Shell Prompt의 모양을 사용자 입맛대로 바꿀 수 있습니다. 단순한 색상 변경은 물론이고, 표시되는 정보까지 바꿀 수 있습니다.

Ubuntu를 설치하고 최초에는 프롬포트의 형태가 다음과 같은 모양입니다.

user@my.server.com:/home/user/blahblah/Andromeda/$ 

이렇게 표시되는 프롬포트을 바꿀 수 있다는건 예전부터 알고 있었지만, 그간 딱히 불편함을 느꼈던 것은 아니었으므로 그냥 사용해 왔습니다.

헌데, 근래에 들어서 작업하는 디렉토리 깊이가 좀 깊어졌는데, 입력칸이 저~기 오른쪽 끝에 가 있거나 심지어 줄바꿈이 되는 일도 심심치 않게 일어났습니다.. =.=;;

결국 구글링을 통해 이걸 바꾸는 방법을 찾아내서 곧바로 적용하였습니다. 커스터마이징한 프롬포트의 모양은 대략 다음과 같습니다.

 
 [03:09:15]
! /home
 user@tuwlab.com$

우선, Shell이 세 줄로 표시되게 변경하였습니다. 첫 번째 줄은 이전 Shell과 구분을 명확하게 하기 위해 공란을 두었고, 다음 줄에는 현재 시각과 디렉토리 경로가 표시되도록 하였습니다. 마지막 번째 줄은 사용자명과 서버 이름만 표시합니다.

역상 모양의 빨간 느낌표는 직전에 실행한 명령이 올바르게 종료되지 못했을 경우에만 나타납니다. 간혹 오류메시지를 출력하지 않는 프로그램이 올바르게 종료되지 않았을 경우 이것을 감지하기 위한 목적입니다.

프롬포트의 색깔이나 모양을 수정하려면 ColorGCC처럼 별도의 패키지를 설치해야 하는 줄 알았는데 그게 아니었습니다. 홈 디렉토리에 있는 .bashrc 파일만 적절히 수정해 주면 프롬포트를 이렇게 컬러풀하고 유용하게 바꿀 수 있습니다.


우선 .bashrc 파일을 열고 색상 표시를 활성화하기 위해 다음 줄의 주석을 해제합니다.

color_prompt=yes

조금 더 아래로 내려가보면 다음과 같은 줄이 보입니다.

...
if [ "$color_prompt" = yes ]; then
...

이 줄 윗부분에 다음 내용을 복붙해 넣습니다. Style 관련 Escape 구문들이 상당히 지저분하기 때문이 이렇게 매크로 상수로 지정해 놓고 쓰면 편리합니다.

...
# Console Style Constants
RST="\[\e[0m\]"           # Reset Styles
BOLD="\[\e[1m\]"          # Bold
UL="\[\e[4m\]"            # Underline
HL="\[\e[7m\]"            # Highlight (inverse)
FG_BLACK="\[\e[90m\]"     # Foreground black
FG_RED="\[\e[91m\]"       # Foreground red
FG_GREEN="\[\e[92m\]"     # Foreground green
FG_YELLOW="\[\e[93m\]"    # Foreground yellow
FG_BLUE="\[\e[94m\]"      # Foreground blue
FG_MAGENTA="\[\e[95m\]"   # Foreground magenta
FG_CYAN="\[\e[96m\]"      # Foreground cyan
FG_WHITE="\[\e[97m\]"     # Foreground white
BG_BLACK="\[\e[100m\]"    # Background black
BG_RED="\[\e[101m\]"      # Background red
BG_GREEN="\[\e[102m\]"    # Background green
BG_YELLOW="\[\e[103m\]"   # Background yellow
BG_BLUE="\[\e[104m\]"     # Background blue
BG_MAGENTA="\[\e[105m\]"  # Background magenta
BG_CYAN="\[\e[106m\]"     # Background cyan
BG_WHITE="\[\e[107m\]"    # Background white

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
...

* 각 색상의 Intensity 옵션으로 Normal Mode와 Bright Mode를 지정할 수 있는데, 여기서는 모두 Bright 모드를 사용했습니다. Normal Mode에 비해 Bright Mode는 색이 좀 더 밝게 표시됩니다. Normal Mode 색상을 사용하고자 할 때는 다음 링크를 참조하여 숫자를 바꿔주도록 합니다.

▶ ANSI Esapce Code : http://en.wikipedia.org/wiki/ANSI_escape_code

이제 저 아래에 있는 PS1 상수를 적절하게 수정하면 프롬포트의 모양을 지정해 줄 수 있습니다. 우선, 사용 가능한 Escape 문자들은 다음과 같다.

  • \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 portion 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)
  • \V : the release of bash, version + patch level (e.g., 2.00.0)
  • \w : the current working directory, with $HOME abbreviated with a tilde
  • \W : the basename of the current working directory, with $HOME abbreviated with a tilde
  • \! : the history number of this command
  • \# : the command number of this command
  • \$ : if the effective UID is 0, a #, otherwise a $
  • \nnn : the character corresponding to the octal number nnn
  • \\ : a backslash
  • \[ : begin a sequence of non-printing characters, which could be used to embed a terminal control sequence into the prompt
  • \] : end a sequence of non-printing characters

( 참조 : http://www.cyberciti.biz/tips/howto-linux-unix-bash-shell-setup-prompt.html )

위에서 정의한 매크로 상수와 Escape 문자들을 조합하여 PS1 변수를 재정의 해 주도록 합니다.

예를 들어, 지금 제가 사용하고 있는 PS1 변수는 다음과 같습니다. 지저분한 Style 관련 Escape 구문들을 상수로 치환해서 작성했기 때문에 어렵지 않게 문법을 이해할 수 있을 것입니다.

    PS1="\n${FG_MAGENTA}[\t]${RST}\`if [ \$? != 0 ]; then echo ' ${FG_RED}${BOLD}${HL}!${RST}'; fi\` ${FG_YELLOW}\\
w${RST}\n${debian_chroot:+($debian_chroot)}${FG_GREEN}${BOLD}\u${RST}${FG_WHITE}@${RST}${FG_CYAN}\h${RST}\$ "

수정을 완료한 뒤 다음 명령어를 쳐서 .bashrc를 Reload해 줍니다.

. ~/.bashrc


서비스 선택
이용중인 SNS 버튼을 클릭하여 로그인 해주세요.
SNS 계정을 통해 로그인하면 회원가입 없이 댓글을 남길 수 있습니다.
댓글
?
Powered by SocialXE

List of Articles
번호 분류 제목 글쓴이 최근 수정일 조회 수
50 Linux 한글 입력기 나비(Nabi)에서 한/영 키가 인식되지 않는 경우 file TUW 2017.06.02 2410
49 Linux [VirtualBox] Windows 7 물리 디스크 부팅 (Raw Disk Booting or Native Booting) - 방법 1 file TUW 2017.06.14 2959
48 Linux [Linux] Screen 터미널 에뮬레이션 프로그램 사용하기 TUW 2015.08.19 3046
47 Linux Intelli Backup: File system 및 Database 백업 자동화 Bash 스크립트 TUW 2017.06.14 3257
46 Linux [VirtualBox] 가상머신 Windows 7 에서 Aero 기능 활성화하기 file TUW 2017.06.02 3312
45 Linux [VirtualBox] Windows 7 물리 디스크 부팅 (Raw Disk Booting or Native Booting) - 배경 file TUW 2017.06.02 5430
44 Linux TCPDump를 활용하여 패킷 모니터링하기 TUW 2020.04.13 7217
43 Linux [Bash] 자동완성 스크립트(Completion Script) 작성 방법과 동작 원리 TUW 2019.08.28 7672
42 Linux [Linux] Sudo 명령의 Secure Path TUW 2015.04.24 8153
41 Linux [Linux] fdisk 활용 외: 파티션 생성, 배드블록 검사, 파일시스템 생성 TUW 2015.04.24 8252
40 Linux [ColorGCC] 컴파일 경고 및 오류메시지 컬러로 출력하기 file TUW 2017.06.02 9689
39 Linux SSHFS를 활용한 원격 디렉토리 마운트 TUW 2014.04.24 10075
38 Linux [Ubuntu] 원격 Shell에서 로그인 사용자 디스플레이에 GUI 프로그램 실행하기 TUW 2016.03.06 10114
37 Linux Ubuntu에서 PHP 최신버전 업데이트하기 TUW 2014.04.23 11025
36 Linux [Vi/Vim] 단축키 모음 file TUW 2017.06.02 11557
35 Linux [Emacs] 주요 단축키 모음 file TUW 2017.06.02 11582
목록
Board Pagination Prev 1 2 3 4 Next
/ 4

Powered by Xpress Engine / Designed by Sketchbook

sketchbook5, 스케치북5

sketchbook5, 스케치북5