Bash (简体中文)

From ArchWiki
Revision as of 11:36, 15 October 2012 by Jaurung (talk | contribs)
Jump to navigation Jump to search

Tango-preferences-desktop-locale.png本页面需要更新翻译,内容可能已经与英文脱节。要贡献翻译,请访问简体中文翻译组Tango-preferences-desktop-locale.png

附注: please use the first argument of the template to provide more detailed indications.

Bash (Bourne-again Shell) 是一个外壳/编程语言,来自 GNU Project。它的名字是向它的前身——很早以前的 Bourne shell 致敬。Bash 可以运行在大部分类 UNIX 操作系统中,包括 GNU/Linux。

调用

Bash调用方式的不同会导致Bash运行方式的不同。下面是在不同模式下运行的Bash的描述。

登录外壳

如果Bash由在tty中的登录, SSH 守护进程, 或者其它类似的方式而派生出来, 它就被称为登录外壳(shell)。你可以使用命令行选项-l 或者 --login 来使用这个种模式。

交互式外壳

如果Bash在启动的时候既没有使用 -c 选项也没有使用非选项参数,那我们就认为它是一个交互式外壳,同时Bash的标准输出和标准错误被链接到终端上。

符合 POSIX

通过在Bash启动时使用 --posix 命令行参数或者在启动后执行 ‘set -o posix’ 来使Bash在增强的POSIX标准下运行。

传统模式

在Arch下 /bin/sh (过去是Bourne shell)被符号链接至/bin/bash.

如果以命令名sh来调用Bash, Bash会尽可能地模仿历史版本的sh的启动过程。

配置

Tango-edit-clear.pngThis article or section needs language, wiki syntax or style improvements. See Help:Style for reference.Tango-edit-clear.png

Reason: please use the first argument of the template to provide a brief explanation. (Discuss in Talk:Bash (简体中文)#)

配置文件概览

  • /etc/profile
  • ~/.bash_profile
  • ~/.bash_login
  • ~/.profile
  • /etc/bash.bashrc (非标准: 只对部分发行版有效,Arch包含在这部分中)
  • ~/.bashrc
  • ~/.bash_logout

对经常使用的配置文件的概述:

/etc/profile

/etc/profile被所有兼容Bourne shell的shell在登录时引用。它在登录时建立了环境并且加载了应用程序特定(/etc/profile.d/*.sh)的设置。

.profile

此文件在启动一个交互式的登录shell时被Bash所读入和引用。

.bashrc

此文件在启动一个交互式的非登录shell时被Bash所读入和引用。比如当你从桌面环境中打开一个虚拟控制台时。这个文件在用户自定义自己的shell环境时特别有用。

配置文件在启动时的引用顺序

这些文件在不同的情形下被Bash所引用。

  • 如果交互式+登录shell → /etc/profile 然后按以下顺序读取 ~/.bash_profile, ~/.bash_login, and ~/.profile
    • Bash会在退出时引用{ic|~/.bash_logout}}。
  • 如果交互式+非登录shell → /etc/bash.bashrc 然后 ~/.bashrc
  • 如果交互式+传统模式 → /etc/profile 然后 ~/.profile

但是,在Arch下,默认的:

  • /etc/profile (间接地) 引用 /etc/bash.bashrc
  • /etc/skel/.bash_profile Arch鼓励用户将/etc/skel/.bash_profile复制到 ~/.bash_profile, 并引用 ~/.bashrc

这意味着 /etc/bash.bashrc~/.bashrc 将会为所有的交互式shell所执行, 不管它是不是登录shell.

用户dotfiles的例子可以在/etc/skel/中被找到。

Note: legacy mode is when invoked with the name sh

外壳和环境变量

Bash的行为和通过它来运行的程序会被许多的环境变量所影响。环境变量被用于储存有用的值比如命令搜索路径,或者使用哪个浏览器。当一个新的shell或者脚本被执行时,这个shell会继承它的父shell的变量, 因此这个shell会以内部的shell变量启动[1]

这些Bash中的shell变量可以被导出以变成环境变量:

VARIABLE=content
export VARIABLE

或者快捷地:

export VARIABLE=content

环境变量依照惯例放置在~/.profile或者/etc/profile,这样所有兼容Bourne shell的shell都可以使用。

参阅Environment Variables以获得更加全面的信息。

命令行

Bash的命令行由一个叫做Readline的分离库来管理。Readline提供了很多Bash命令行交互的快捷键,比如说,光标单词间向前向后移动,删除单词等等。管理输入历史也是Readline的职责。最后一点也非常重要, 它允许你创造

别名

别名是一个命令, 它让用其它字符串替代一句话称为可能。这个命令常常被用来缩短系统命令,或者用来将默认参数加入到常用命令中。

用户个人的别名最好保存在~/.bashrc, 而系统级的别名(这些别名会影响所有用户)存放在/etc/bash.bashrc

摘录于~/.bashrc的一个例子涵盖了为节约时间而写的别名:

~/.bashrc
# modified commands
alias diff='colordiff'              # requires colordiff package
alias grep='grep --color=auto'
alias more='less'
alias df='df -h'
alias du='du -c -h'
alias mkdir='mkdir -p -v'
alias nano='nano -w'
alias ping='ping -c 5'
alias ..='cd ..'

# new commands
alias da='date "+%A, %B %d, %Y [%T]"'
alias du1='du --max-depth=1'
alias hist='history | grep $1'      # requires an argument
alias openports='netstat --all --numeric --programs --inet --inet6'
alias pg='ps -Af | grep $1'         # requires an argument (note: /usr/bin/pg is installed by the util-linux package; maybe a different alias name should be used)

# privileged access
if [ $UID -ne 0 ]; then
    alias sudo='sudo '
    alias scat='sudo cat'
    alias svim='sudo vim'
    alias root='sudo su'
    alias reboot='sudo reboot'
    alias halt='sudo halt'
    alias update='sudo pacman -Su'
    alias netcfg='sudo netcfg2'
fi

# ls
alias ls='ls -hF --color=auto'
alias lr='ls -R'                    # recursive ls
alias ll='ls -l'
alias la='ll -A'
alias lx='ll -BX'                   # sort by extension
alias lz='ll -rS'                   # sort by size
alias lt='ll -rt'                   # sort by date
alias lm='la | more'

# safety features
alias cp='cp -i'
alias mv='mv -i'
alias rm='rm -I'                    # 'rm -i' prompts for every file
alias ln='ln -i'
alias chown='chown --preserve-root'
alias chmod='chmod --preserve-root'
alias chgrp='chgrp --preserve-root'

# pacman aliases (if applicable, replace 'pacman' with 'yaourt'/'pacaur'/whatever)
alias pac="pacman -S"      # default action     - install one or more packages
alias pacu="pacman -Syu"   # '[u]pdate'         - upgrade all packages to their newest version
alias pacs="pacman -Ss"    # '[s]earch'         - search for a package using one or more keywords
alias paci="pacman -Si"    # '[i]nfo'           - show information about a package
alias pacr="pacman -R"     # '[r]emove'         - uninstall one or more packages
alias pacl="pacman -Sl"    # '[l]ist'           - list all packages of a repository
alias pacll="pacman -Qqm"  # '[l]ist [l]ocal'   - list all packages which were locally installed (e.g. AUR packages)
alias paclo="pacman -Qdt"  # '[l]ist [o]rphans' - list all packages which are orphaned
alias paco="pacman -Qo"    # '[o]wner'          - determine which package owns a given file
alias pacf="pacman -Ql"    # '[f]iles'          - list all files installed by a given package
alias pacc="pacman -Sc"    # '[c]lean cache'    - delete all not currently installed package files
alias pacm="makepkg -fci"  # '[m]ake'           - make package from PKGBUILD file in current directory

函数

Bash also support functions. The following function will extract a wide range of compressed file types. Add the function to ~/.bashrc and use it with the syntax extract <file1> <file2> ...

~/.bashrc
extract() {
    local c e i

    (($#)) || return

    for i; do
        c=''
        e=1

        if [[ ! -r $i ]]; then
            echo "$0: file is unreadable: \`$i'" >&2
            continue
        fi

        case $i in
        *.t@(gz|lz|xz|b@(2|z?(2))|a@(z|r?(.@(Z|bz?(2)|gz|lzma|xz)))))
               c='bsdtar xvf';;
        *.7z)  c='7z x';;
        *.Z)   c='uncompress';;
        *.bz2) c='bunzip2';;
        *.exe) c='cabextract';;
        *.gz)  c='gunzip';;
        *.rar) c='unrar x';;
        *.xz)  c='unxz';;
        *.zip) c='unzip';;
        *)     echo "$0: unrecognized file extension: \`$i'" >&2
               continue;;
        esac

        command $c "$i"
        e=$?З
    done

    return $e
}
Note: Bash users should make sure extglob is enabled: shopt -s extglob, for example by adding it to the .bashrc. It is enabled by default if using Bash completion. Zsh users should do: setopt kshglob instead.

Another way to do this is to install unp package.

提示与技巧

自定义提示符

The bash prompt is governed by the variable $PS1. To colorize the bash prompt, first comment out the default $PS1:

#PS1='[\u@\h \W]\$ '

Then add the following line:

PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[0;31m\]\$ \[\e[m\]\[\e[0;32m\] '

This $PS1 is useful for a root bash prompt, with red designation and green console text. For details on customizing your bash prompt, see Color Bash Prompt.

自动命令补全

It is useful to have the auto-complete feature (pressing Template:Keypress key twice on the keyboard) after you type some command like sudo.

To do this add a line in this format to your ~/.bashrc file:

complete -cf your_command

For example, to enable auto-complete after sudo and man:

complete -cf sudo
complete -cf man

高级的补全方法

Despite Bash's native support for basic file name, command, and variable auto-completion, there are ways of improving and extending its reach.

The bash-completion package extends functionality by adding auto-completion to a wide range of commands and their options. Enabling advanced bash completion is quite simple, just install the following package:

# pacman -S bash-completion

Start a new shell and it will be automatically enabled thanks to /etc/bash.bashrc.

更快的补全操作

By appending the following into the readline initialization file (~/.inputrc or /etc/inputrc by default):

set show-all-if-ambiguous on

it is no longer necessary to hit Template:Keypress (default binding) twice to produce a list of all possible completions (both when a partial completion is possible and when no completion is possible), as a single key-press will suffice. Alternatively, to produce such a list only when no completion is possible (i.e., not when a partial completion is possible), append the following command in lieu of the previous one:

set show-all-if-unmodified on

命令未找到时的钩子拓展(HOOKS)

终端中禁用 Ctrl+z

You can disable Template:Keypress (pauses/closes your CLI application) feature for you CLI by wrapping your command in this script

#!/bin/bash
trap "" 20
/path_to_your_application/

example:

#!/bin/bash
trap "" 20
/usr/bin/adom

With this example script, when you accidentally press Template:Keypress instead of Template:Keypress or some other key combination while playing Adom(game) your game will not end. Nothing will happen because Template:Keypress will be ignored.

登出后清空屏幕

To clear the screen after logging out on a virtual terminal, append the following lines to ~/.bash_logout:

clear
reset

ASCII art, fortunes and cowsay

Along with a colors, system info and ASCII symbols, Bash can be made to display a piece of ASCII art on login. ASCII images can be found online and pasted into a text file, or generated from scratch. To set the image to display in a terminal on login, place the string

cat /path/to/text/file

at the top of ~/.bashrc.

Random poignant, inspirational, silly or snide phrases can also be shown. To see an example, install the fortune-mod package from the extra repository.

(user@host)-(10:10 AM Wed Dec 22)
--(~)--->  fortune

It is Texas law that when two trains meet each other at a railroad crossing, each shall come to a full stop, and neither shall proceed until the other has gone.

To have a random phrase displayed when logging into a terminal, just set

command fortune

as the top line in ~/.bashrc.

Note: By default, fortune displays quotes and phrases that are rather inoccuous. However, the package does contain a set of comments some will find offensive, located in /usr/share/fortune/off. See the man page for more info on these.

These two features can be combined, using the program cowsay. Modify the line at the top of ~/.bashrc to read

command cowsay $(fortune)

or

command cowthink $(fortune)


The earth is like a tiny grain of sand, 
only much, much heavier.                
----------------------------------------- 
       \   ^__^
        \  (oo)\_______
           (__)\       )\/\
               ||----w |
               ||     ||

The ASCII images are generated by .cow text files located in /usr/share/cows, and all themes can be listed with the command cowsay -l These files can be edited to the user's liking; custom images can also be created from scratch or found on the net. The easiest way create a custom cow file from an image found online would be to open an existing .cow file in a text editor, copy-and-paste the image from a browser and save the file as a different name. Test the custom file using

# cowsay -f cowfile $(fortune)

This can produce some nice eye candy, and the commands used can be more complex. For a specialized example, take a look here. Another example, to use a random cow, random facial expression, and nicely wrap the text of long fortunes.

fortune -a | fmt -80 -s | cowsay -$(shuf -n 1 -e b d g p s t w y) -f $(shuf -n 1 -e $(cowsay -l | tail -n +2)) -n
 ________________________________________ 
( Fry: I must be a robot. Why else would )
( human women refuse to date me?         )
---------------------------------------- 
       o
         o
           o  
              ,'``.._   ,'``.
             :,--._:)\,:,._,.:
             :`--,@@@:`...';\        
              `,'@@@@@@@`---'@@`.     
              /@@@@@@@@@@@@@@@@@:
             /@@@@@@@@@@@@@@@@@@@\
           ,'@@@@@@@@@@@@@@@@@@@@@:\.___,-.
          `...,---'``````-..._@@@@|:@@@@@@@\
            (                 )@@@;:@@@@)@@@\  _,-.
             `.              (@@@//@@@@@@@@@@`'@@@@\
              :               `.//@@)@@@@@@)@@@@@,@;
              |`.            _,'/@@@@@@@)@@@@)@,'@,'
              :`.`-..____..=:.-':@@@@@.@@@@@_,@@,'
             ,'\ ``--....-)='    `._,@@\    )@@@'``._
            /@_@`.       (@)      /@@@@@)  ; / \ \`-.'
           (@@@`-:`.     `' ___..'@@_,-'   |/   `.)
            `-. `.`.``-----``--,@@.'
              |/`.\`'        ,',');
                  `         (/  (/
(user@host)-(10:10 AM Wed Dec 22)--(~))--->

ASCII Historical Calendar

To install calendar files in your ~/.calendar directory:

$ mkdir -p ~/.calendar
$ curl -o calendar.rpm http://download.fedora.redhat.com/pub/epel/5/x86_64/calendar-1.25-4.el5.x86_64.rpm
$ rpm2cpio calendar.rpm | bsdtar -C ~/.calendar --strip-components=4 -xf - ./usr/share/c*

This will then print out the calendar items

$ sed -n "/$(date +%m\\/%d\\\|%b\*\ %d)/p" $(find ~/.calendar /usr/share/calendar -maxdepth 1 -type f -name 'c*' 2>/dev/null);

Customise Title

The $PROMPT_COMMAND variable allows you to execute a command before the prompt. For example, this will change the title to your full current working directory:

export PROMPT_COMMAND='echo -ne "\033]0;$PWD\007"'

资源