Share to: share facebook share twitter share wa share telegram print page

Alias (命令)

计算机运算中,alias 是许多命令行界面的命令,比如 Unix shell4DOS/4NTWindows PowerShell 等,它给用户提供了别名——也就是用自定义字符串替换指定命令的功能,通常用于简写系统命令,或给常用命令添加默认选项,MS-DOSMicrosoft Windows 操作系统內,通常使用 DOSKey 命令定义别名。

alias 命令的作用时间是命令运行之后到 shell 会话结束,经常使用的别名可在 shell 的配置文件比如 C Shell(csh)的 ~/.cshrcBourne Again Shell~/.bashrc 里定义,如此当相应的 shell 会话启动后就可以使用这些自定义的别名了。alias 命令可以直接写入这些配置文件,或单独放在一个文件,比如 .alias 里,或依用户使用的解释器分别定义于 .alias-bash,.alias-csh 等文件,然后使用 source 命令执行该文件来设定。

定义别名

别名可以使用给 alias 命令指定键值对参数的方式定义,在 Bash 內,语法如下:

alias copy='cp'

同样的别名,在 csh 或 tcsh 里可以这样指定:

alias copy "cp"

这个别名的作用,是当用户在命令行內输入 copy 时,命令行解释器会把该命令替换为 cp 命令来执行。

在 4DOS/4NT 命令行內,可以使用以下命令把 cp 定义为 4DOS 的 copy 命令的别名:

alias cp copy

要在 Windows PowerShell 內定义别名,可以使用以下命令:

new-alias ci copy-item

以上命令给 Windows PowerShell 的 copy-item 命令定义了一个别名 ci,因此用户在 Windows PowerShell 里输入 ci 时,实际执行的是 copy-item 命令。

历史

Unix 內,alias 命令是由 C shell 引入的,之后也被加入到 tcsh 和 Bash 內。C shell 的别名被严格限制在一行里,复杂的 shell 语言则需要多行,不过单行别名对建立快捷的命令仍然很有用。Bourne shell(sh)內没有别名功能,但它有更强大的 shell 函数方式。Bash 和 Korn shell(ksh)则同时支持函数和别名,并建议在可能时尽量使用函数。

查看當前已定義的别名

要查看當前命令行已定義的别名,可以用以下命令:

alias          # 不帶參數運行 alias 命令,可顯示當前已定義的别名列表
alias -p       # 同上,但在 4DOS/4NT 和 PowerShell 里無效
alias myAlias  # 顯示指定别名取代的實際命令

忽略别名

在 Unix shells 里,如果别名已经指定过,可以把命令放在引号里,或在前面添加一个反斜杠来使别名定义失效。比如,若已定义了以下别名:

alias ls='ls -la'

要使以上别名失效并强制执行原始的 ls 命令,可使用以下语法:

'ls'

\ls

在 4DOS/4NT 命令行里,则可以在命令前面添加星号来使已定义的别名失效,比如,可用以下方式定义别名:

alias dir = *dir /2/p

第二个 dir 命令前的星号,确保其运行的是原始的 dir 命令,避免递归地别名展开,用户还可以运行以下命令,确保运行的是原始(未设定别名的)dir 命令:

*dir

更改别名

在 Windows PowerShell 里,可使用以下命令更改一个已经存在的别名:

set-alias ci cls

运行以上命令后,ci 将变成 cls 命令的别名。


删除别名

在 Unix shell 和 4DOS/4NT 里,别名可以通过 unalias 命令清除:

 unalias copy          # 删除 copy 别名
 unalias -a            # -a 选项会清除所有已定义的别名,此选项在 4DOS/4NT 里无效
unalias *             # 4DOS/4NT 的清除别名命令,支持通配符

在 Windows PowerShell 里,别名可用以下命令删除:

 remove-item alias:ci  # 删除别名 ci

特性

Chaining

别名通常只替换第一个词,但有些命令行解释器,比如 Bash 和 ksh 允许替换一个字符序列或几个单词,这个特性使用 shell 函数方式是做不到的。

通常的语法是在第一个定义的别名所替换的命令后加一个空格,比如定义以下两个别名:

alias list='ls '      # 注意 ls 后面的空格
alias long='-Flas'    # ls 的选项

然后可运行

list long myfile      # 运行时被解释为 ls -Flas myfile

来列出文件详细信息,可见命令行解释器对 long 也进行了别名展开。

别名里的引用

要使用单引号定义一个里面带有单引号的别名,比如要给以下 perl 脚本定义别名:

 $ perl -pe 's/^(.*) foo/$1 bar/;'

你不能这样简单转义:

 $ alias foo2bar='perl -pe \'s/^(.*) foo/$1 bar/;\'' # 错误:反斜杠并不会对后一个字符进行转义

不过,可以这样:

 $ alias foo2bar='perl -pe '\''s/^(.*) foo/$1 bar/;'\''' # 把反斜杠放在引号里使之成为 '\'

但你可以在双引号里使用单引号。[1]

 $ alias foo2bar='perl -pe '"'"'s/^(.*) foo/$1 bar/;'"'"''

你也可以使用 shell 函数方式,而非使用别名。

命令参数

在 C Shell 里,命令的参数可以通过字符串 \!* 嵌入到别名定义里,比如定义以下别名:

alias l-less 'ls \!* | less'

然后执行 l-less /etc /usr,命令会被展开成 ls /etc /usr | less,即列出 /etc 和 /usr 两个目录的文件,且满屏后暂停,若没有 \!*

alias l-less 'ls | less'

会被展开成 ls | less /etc /usr,这将会错误的试图用 less 打开后两个目录。[2]

Bash 和 Korn shell 里,可以使用 shell 函数做到,参见下文的备选段落。

典型别名

Bash 里一些常用的别名:

alias ls='ls --color=auto' # 输出显示为彩色
alias la='ls -Fa'          # 列出所有文件
alias ll='ls -Fls'         # 列出文件详细信息

alias rm='rm -i'           # 删除前需确认
alias cp='cp -i'           # 覆盖前需确认
alias mv='mv -i'           # 覆盖前需确认

alias vi='vim'             # 输入 vi 命令时使用 vim 编辑器

Windows PowerShell 的标准别名:

new-alias cd set-location

new-alias ls get-childitem
new-alias dir get-childitem

new-alias echo write-output
new-alias ps get-process
new-alias kill stop-process

备选

别名应保持简单,否则应考虑以下备选方式:

  • 命令脚本,通过脚本可以创建新的系统命令。
  • 符号链接,可放在 /usr/local/bin 给所有用户使用,或放在用户自己的 $HOME/bin 目录,只供自己使用。这提供了一个调用命令的新方式,并在某些情况下,对少数支持使用调用名选择操作模式的命令,允许使用其隐含的命令函数。
  • Shell 函数,特别是如果命令需要修改 shell 内部运行环境(如环境变量)、改变当前工作目录、或在非交互 shell 使用情况下出现在搜索路径里面(特别是“较安全的” rmcpmv 版本等等)。

别名最常见的使用方式,是给命令添加常用的选项,这可以使用定义简单 Shell 函数的方式代替:

 alias ll='ls -Flas'              # 列出文件详细信息,别名方式
 ll () { ls -Flas "$@" ; }        # 列出文件详细信息,Shell 函数方式

ls 本身定义成函数,可以用以下方式定义(注意这是 Bash 的 ls 命令,较老的 Bourne shell 需要使用 /bin/ls 代替):

 ls () { command ls --color=auto "$@" ; }

参考资料

  1. ^ StackOverflow 上的解释. [2014-03-23]. (原始内容存档于2013-07-03). 
  2. ^ 给别名传递参数的示例. [2014-03-23]. (原始内容存档于2012-11-25). 

外部链接

Read other articles:

この項目では、朝日放送テレビ制作でテレビ朝日系列の全国ネット番組について説明しています。同じく『だいどころ』を称する毎日放送制作の料理番組『dai-docoro☆ベジタ』については「ダイエー#メディア・番組等」をご覧ください。 プロジェクト‐ノート:放送または配信の番組#日本国内のバラエティ・情報・報道番組などの記事の放送リスト・ネット局の記述添削(…

Travel document issues to a refugee See also: Certificate of identity and Refugee identity certificate A sample refugee travel document The bio-data page of an Australian refugee travel document issued to a Chinese refugee The bio-data page of a New Zealand refugee travel document issued to a Chinese refugee A refugee travel document (also called a 1951 Convention travel document or Geneva passport) is a travel document issued to a refugee by the state in which they normally reside in allowing t…

Pemilihan umum Bupati Puncak Jaya 20172012202415 Februari 2017[1]15 Juni 2017 (PSU)Kandidat   Calon Yuni Yustus Henok Partai PDI-P PPP Demokrat Pendamping Deinas Kirenius Rinus Suara Popular 74.125 61.442 34.750 Persentase 43,52% 36,07% 20,40% Peta persebaran suara Berkas:PAPUA - KAB. PUNCAK JAYA.pngLokasi Kabupaten Puncak Jaya di Provinsi Papua Bupati petahanaHenok Ibo Demokrat Bupati terpilih Yuni Wonda PDI-P Sunting kotak info • L • BBantuan penggunaan templat …

Сен-Сьєрж-ла-СеррSaint-Cierge-la-Serre Країна  Франція Регіон Овернь-Рона-Альпи  Департамент Ардеш  Округ Прива Кантон Ла-Вульт-сюр-Рон Код INSEE 07221 Поштові індекси 07800 Координати 44°47′39″ пн. ш. 4°41′14″ сх. д.H G O Висота 179 - 829 м.н.р.м. Площа 16,2 км² Населення 248 (01-2020[1]) Г

Form of residence permit Working holiday redirects here. For the album and music festival, see Working Holiday! A working holiday visa is a residence permit allowing travellers to undertake employment (and sometimes study) in the country issuing the visa to supplement their travel funds. For many young people, holding a working holiday visa enables them to experience living in a foreign country without having to find work sponsorship in advance or going on an expensive university exchange progra…

Wappenemblem einer Basilica maior: die Schlüssel Petri und das Umbraculum Als Basilicae maiores (Singular Basilica maior) werden die ranghöchsten römisch-katholischen Kirchen bezeichnet. Alle anderen Kirchen, die den Titel einer Basilika führen, sind Basilicae minores. Das erste Dokument, das den Begriff Basilica maior benennt, stammt aus dem Jahr 1727. Inhaltsverzeichnis 1 Übersicht 2 Merkmale 3 Liste der Basilicae maiores 4 Literatur 5 Einzelnachweise Übersicht Die vier Basilicae maiores…

Kintetsu-Nagoyastazione ferroviaria近鉄名古屋 Vista del fabbricato viaggiatori LocalizzazioneStato Giappone LocalitàNakamura-ku, Nagoya Coordinate35°10′08.9″N 136°53′03.5″E / 35.169139°N 136.884306°E35.169139; 136.884306Coordinate: 35°10′08.9″N 136°53′03.5″E / 35.169139°N 136.884306°E35.169139; 136.884306 Linee● Linea Kintetsu Nagoya StoriaStato attualeIn uso Attivazione1938 CaratteristicheTipoStazione sotterranea di testa Bina…

Чопенко Олександр Анатолійович  Старший сержант Загальна інформаціяНародження 30 жовтня 1969(1969-10-30)СаївкаСмерть 17 січня 2018(2018-01-17) (48 років)ГранітнеПсевдо «Колдун»Військова службаРоки служби 2014-2018Приналежність  УкраїнаВид ЗС Сухопутні військаРід військ  Механізов

Ginny SimmsSimms pada sekitar tahun 1943Informasi latar belakangNama lahirVirginia Ellen SimmsNama lainVirginia E. EastvoldLahir(1913-05-25)25 Mei 1913San Antonio, Texas, Amerika SerikatMeninggal4 April 1994(1994-04-04) (umur 80)Palm Springs, California, Amerika SerikatPekerjaanPenyanyi, pemeranTahun aktif1932–1951Label Brunswick Vocalion Okeh Columbia Sonora Artis terkaitOrkestra Kay KyserSitus webginnysimms.com Virginia Ellen Simms[1] (25 Mei 1913 – 4 April 1994)…

Tirto UtomoInformasi pribadiLahirKwa Sien Biauw(1930-03-09)9 Maret 1930 Wonosobo, Jawa Tengah, Hindia BelandaMeninggal16 Maret 1994(1994-03-16) (umur 64) Wonosobo, Jawa Tengah, IndonesiaSuami/istriLisa Utomo (Kwee Gwat Kien)[1]PekerjaanPengusahaSunting kotak info • L • B Tirto Utomo atau Kwa Sien Biauw (9 Maret 1930 – 16 Maret 1994) adalah pengusaha Indonesia. Lulusan Fakultas Hukum Universitas Indonesia ini dikenal sebagai pendiri Aqua Golden Mississip…

Biografi ini memerlukan lebih banyak catatan kaki untuk pemastian. Bantulah untuk menambahkan referensi atau sumber tepercaya. Materi kontroversial atau trivial yang sumbernya tidak memadai atau tidak bisa dipercaya harus segera dihapus, khususnya jika berpotensi memfitnah.Cari sumber: Wardina Safiyyah – berita · surat kabar · buku · cendekiawan · JSTOR (Pelajari cara dan kapan saatnya untuk menghapus pesan templat ini) Artikel ini perlu dikembangkan agar…

Nancy WuLahirNancy Wu Tingyan9 September 1981 (umur 42)Hong KongPekerjaanAktrisTahun aktif2001–sekarangPasanganDeep Ng (2006-2008)Kenneth Ma (2008-2010) Patt Sham (2011-2014)Terry Chan (2015-2016) Nancy Wu Karier musikNama lainnancy, 小定, nan, 定定, nannAsalHong Kong Nancy Wu (Hanzi: 胡定欣) (lahir 9 September 1981) adalah seorang aktris asal Hong Kong yang berada di bawah naungan TVB. Ia telah dua kali berturut-turut meraih TVB Anniversary Award untuk Aktris Terbaik dala…

Private Seventh-day Adventist college in Angwin, California, U.S. This article may rely excessively on sources too closely associated with the subject, potentially preventing the article from being verifiable and neutral. Please help improve it by replacing them with more appropriate citations to reliable, independent, third-party sources. (January 2023) (Learn how and when to remove this template message) Pacific Union CollegeFormer namesHealdsburg Academy (1882–1899)Healdsburg College (1899…

Ein suborbitaler Flug ist ein Flug in den Weltraum, der weder dem Schwerefeld des Himmelskörpers entkommt, von dem er startete, noch in eine Umlaufbahn um diesen Körper gelangt (Orbitalflug). Stattdessen fällt das Fluggerät – sofern es nicht mit einem laufenden Antrieb weiter der Schwerkraft entgegenwirkt – wieder zurück auf die Oberfläche. Inhaltsverzeichnis 1 Voraussetzungen 2 Vergleich mit Orbitalflügen 3 Anwendungsgebiete 3.1 Forschungs- und Testflüge 3.2 Start orbitaler Flugger…

Swedish actor (born 1979) This article includes a list of references, related reading, or external links, but its sources remain unclear because it lacks inline citations. Please help to improve this article by introducing more precise citations. (February 2013) (Learn how and when to remove this template message) Shebly NiavaraniBorn (1979-07-07) 7 July 1979 (age 44)Tehran, IranOccupationActor Shebly Niavarani (born 7 July 1979) is a Swedish actor of Persian descent. He studied acting at t…

State of Brazil For the Israeli city, see Acre, Israel. State in BrazilAcreStateEstado do AcreState of Acre FlagCoat of armsMotto(s): Nec Luceo Pluribus Impar (Latin)I do not shine differently from the othersAnthem: Hino do AcreCoordinates: 9°S 70°W / 9°S 70°W / -9; -70Country BrazilCapitalRio BrancoGovernment • GovernorGladson Cameli (PP) • Vice GovernorMailza Gomes (PP) • SenatorsAlan Rick (UNIÃO)Márcio Bittar (UNIÃO)…

American musical 70, Girls, 70Original Broadway WindowcardMusicJohn KanderLyricsFred EbbBookFred Ebb Norman L. MartinBasisBreath of Spring by Peter CokeProductions1971 Broadway 1991 West End 2001 Off-Broadway 2006 Encores! 70, Girls, 70 is a musical with a book by Fred Ebb and Norman L. Martin adapted by Joe Masteroff, lyrics by Ebb, and music by John Kander. The musical is based on the 1958 play Breath of Spring by Peter Coke, which was adapted for the movies in 1960 as Make Mine Mink. The plot…

Tanah RajaDesaNegara IndonesiaProvinsiSumatera UtaraKabupatenSerdang BedagaiKecamatanSei RampahKode pos20995Kode Kemendagri12.18.04.2027 Luas... km²Jumlah penduduk... jiwaKepadatan... jiwa/km² Kantor di satu perkebunan di Tanah Raja (1900-1910) Tanah Raja adalah desa di kecamatan Sei Rampah, Serdang Bedagai, Sumatera Utara, Indonesia. Pranala luar Serdangbedagaikab.go.id Diarsipkan 2009-03-21 di Wayback Machine. lbsKecamatan Sei Rampah, Kabupaten Serdang Bedagai, Sumatera UtaraDesa Cemped…

Analysis of facts to form a judgment For the American drama film, see Critical Thinking (film). Critical thinking is the analysis of available facts, evidence, observations, and arguments in order to form a judgement by the application of rational, skeptical, and unbiased analyses and evaluation.[1] The application of critical thinking includes self-directed, self-disciplined, self-monitored, and self-corrective habits of the mind,[2] thus Critical Thinking is an acquired skill u…

Multiple alphabets of Kurdish language The Kurdistan newspaper established in 1898, was written in the Kurmanji dialect using Arabic script, prior to latinizationThe Kurdish languages are written in either of two alphabets: a Latin alphabet introduced by Celadet Alî Bedirxan in 1932 called the Bedirxan alphabet or Hawar alphabet (after Hawar magazine) and an Arabic script called the Sorani or Central Kurdish alphabet. The Kurdistan Region has agreed upon a standard for Central Kurdish, implemen…

Kembali kehalaman sebelumnya