
是否可以在 bash 腳本中使用“@”符號作為函數名稱?以下不起作用:
function @() {
echo hello
}
答案1
從man bash
name A word consisting only of alphanumeric characters and underscores,
and beginning with an alphabetic character or an underscore. Also
referred to as an identifier.
Shell functions are declared as follows:
name () compound-command [redirection]
function name [()] compound-command [redirection]
答案2
編輯2:雖然@
在 vanilla bash 中沒有問題,但當extglob shell 選項設定完畢後,簡單的echo @()
就可以在一定條件下掛起你的shell了。更有理由不用@
作標識符`。
編輯1:澄清一下,根據標識符的定義,這是不允許的。我不推薦它。我只是說為了向後兼容,它是可能的在 bash 中用作@
識別符。
@() { echo "$1 world"; }
@ hello
alias @="echo hello"
@ world
@
用作特殊參數 ( $@
) 和陣列 ( ${arr[@]}
),但不用於其他地方。 Bash 不會阻止您將它用於別名和函數等標識符,但不會阻止變數名稱。
有些人使用別名@
為sudo
,因此他們可以執行命令為@ apt-get install
。
我不使用它作為 shell 標識符的主要原因@
是我太習慣了@
Makefile 中的語意它使命令靜音而沒有任何副作用。
順便說一句:在 zsh 中的工作原理相同。
答案3
函數的命名與別名允許的字元非常相似:
From man bash
:
字元 /、$、` 和 = 以及上面列出的任何 shell 元字元或引用字元不得出現在別名中。
元字元
以下之一: | &; ( ) < > 空格製表符
所以,除了: / $ ` = | &; ( ) < > 空格製表符
任何其他字元對於別名和函數名都應該有效。
但是,當 extglob 處於作用中時,@
也會使用該字元。@(pattern-list)
預設情況下,extglob 在互動式 shell 中處於作用中狀態。
所以,這應該會失敗:
$ @(){ echo "hello"; }
bash: syntax error near unexpected token `}'
然而,這有效:
$ bash -c '@(){ echo "hello"; }; @'
hello
這也應該有效:
$ shopt -u extglob ### keep this as an independent line.
$ @(){ echo "hello"; }
$ @
hello
也可以這樣做:
$ f(){ echo "yes"; }
$ alias @=f
$ @
yes
別名在接受的符號方面是靈活的。