Настройка bash
Так уж получилось что первый дистрибутив из мира Open Source который довелось мне использовать был Ubuntu Linux 6.06 Собственно я и рад что так получилось, могло же быть и хуже … например, я бы совсем не познакомился с Linux. Ну неважно, дело не в этом, а в том, что так или иначе пришлось осваивать консоль. Командной оболочкой по-умолчанию в Ubuntu (как и в подавляющем большинстве других Linux) есть bash. К чему это я? Да к тому, что даже ставя себе OS из семейства BSD, я всеравно сразу собираю bash. Ну привычен он мне … гораздо более превычен нежели csh или ksh.
Собственно про настойку этой прекрасной оболочки и хотел сказать несколько фраз, а точнее сделать небольшую шпаргалку себе на будущее. Главный конфиг bash-а называется bashrc и располагаться он может, в зависимости от дистрибутива Linux, в /etc или в /etc/bash. Незнаю как кто, но я там ничего не трогаю — использую умолчательные настройки. Но есть еще и доступный для правки «под себя» конфиг в домашней директории каждого пользователя. Найти его можно тут $HOME/.bashrc Как видите — он скрытый. Также bash-ем используются файлы $HOME/.bash_profile и $HOME/.bash_history С .bash_history все есно — тут хранятся выполненные команды командной оболочки bash. А вот что такое .bashrc и .bash_profile — требует пояснений. Назначение этих файлов согласно документации (приведу только нужную часть):
INVOCATION
A login shell is one whose first character of argument zero is a -, or one started with the --login option.
An interactive shell is one started without non-option arguments and without the -c option whose standard input and error are both
connected to terminals (as determined by isatty(3)), or one started with the -i option. PS1 is set and $- includes i if bash is
interactive, allowing a shell script or a startup file to test this state.
The following paragraphs describe how bash executes its startup files. If any of the files exist but cannot be read, bash reports
an error. Tildes are expanded in file names as described below under Tilde Expansion in the EXPANSION section.
When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and exe
cutes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile,
~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The
--noprofile option may be used when the shell is started to inhibit this behavior.
When a login shell exits, bash reads and executes commands from the file ~/.bash_logout, if it exists.
When an interactive shell that is not a login shell is started, bash reads and executes commands from ~/.bashrc, if that file
exists. This may be inhibited by using the --norc option. The --rcfile file option will force bash to read and execute commands
from file instead of ~/.bashrc.
Чтоже получается? А то что .bash_profile отрабатывает когда дело касается авторизиции (вход по ssh например), а .bashrc когда авторизированный пользователь открывает командную оболочку. Поэтому я делаю так, чтобы даже зайдя по ssh у меня подгружался .bashrc
# include .bashrc if it exists
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
# set PATH so it includes user's private bin if it exists
if [ -d ~/bin ] ; then
PATH=~/bin:"${PATH}"
fi
# only for OpenBSD
export PATH="/usr/local/sbin/:${PATH}"
export PKG_PATH=ftp://ftp.openbsd.org/pub/OpenBSD/4.6/packages/`machine -a`/
export TERM="wsvt25m"
Это для OpenBSD. Для Linux можно выкинуть последние 4 строчки 🙂
Ну и, собственно, .bashrc
# don't put duplicate lines in the history. See bash(1) for more options
export HISTCONTROL=ignoredups
export HISTCONTROL=ignorespace
#Если нужно - Proxy Servers
#export http_proxy="http://my.proxy:3128"
#export ftp_proxy=${http_proxy}
## Одна из главных вкусностей - aliases
alias ll='ls -l'
alias la='ls -A'
alias l='ls -CF'
alias lt='ls -lt'
## Colour Prompt
COLOR_RED="\[\033[1;31m\]"
COLOR_WHITE="\[\033[0;00m\]"
COLOR_GREEN="\[\033[0;32m\]"
export PS1="${COLOR_RED}\u${COLOR_WHITE}@${COLOR_RED}\h:${COLOR_WHITE}\w# "
root@gw:~#
Это для пользователя root — у него красное приглашение. Для рядового пользователя она зеленая. Вот конфиг:
## aliases
alias ll='ls -l'
alias la='ls -A'
alias l='ls -CF'
alias lt='ls -lt'
## Colour Prompt
COLOR_RED="\[\033[1;31m\]"
COLOR_WHITE="\[\033[0;37m\]"
COLOR_GREEN="\[\033[0;32m\]"
export PS1="${COLOR_GREEN}\u${COLOR_WHITE}@${COLOR_GREEN}\h:${COLOR_WHITE}\w$ "
root@gw:~#
Выглядит это примерно так:
Чтобы показывать нужный вам цвет PS1 можно использовать в том же .bashrc проверку юзера в духе if $USER = root тогда PS1 с красным приглашением else PS1 — зеленый. Но мне чегото неохота чтобы каждый раз при открытии терминала система это проверяла — один раз написал и все 🙂
В данном случае я задавался целью немного розукрасить bash и придать ему более userfriendly качества. Конечно, это далеко не все что можно настроить через bashrc, поэтому за дополнительной информацией обращайтесь к документации. Удачи! И красочных всем консолей!
Комментов пока нет