发新话题
打印

语法正确的函数定义失败 (alias 的陷阱)

语法正确的函数定义失败 (alias 的陷阱)

一样的函数定义语法, 一个成功, 一个失败:
引用:
-(dearvoid@LinuxEden:Forum)-(~/tmp)-
[$$=6362 $?=0]
; cat rc-2
foo()
{
    echo This is function foo
}
-(dearvoid@LinuxEden:Forum)-(~/tmp)-
[$$=6362 $?=0]
; source rc-2
-(dearvoid@LinuxEden:Forum)-(~/tmp)-
[$$=6362 $?=0]
; foo
This is function foo
-(dearvoid@LinuxEden:Forum)-(~/tmp)-
[$$=6362 $?=0]
; cat rc-1
ls()
{
    echo This is function ls
}
-(dearvoid@LinuxEden:Forum)-(~/tmp)-
[$$=6362 $?=0]
; source rc-1
bash: rc-1: line 1: syntax error near unexpected token `('
bash: rc-1: line 1: `ls()'
-(dearvoid@LinuxEden:Forum)-(~/tmp)-
[$$=6362 $?=1]
; bye
bash 2.05b 和 3.2.39 都有问题

[ 本帖最后由 dearvoid 于 2008-6-18 17:10 编辑 ]      
'
梅须逊雪三分白 雪却输梅一段香

TOP

研究结果如下:
引用:
-(dearvoid@LinuxEden:Forum)-(~/void/bash)-
[$$=7463 $?=0]
; cat confusing-aliases-2.sh
#!/bin/bash

shopt -s expand_aliases

alias foo='echo hello world'

#
# The following definition is the same as this:
#
#   echo hello world()
#   {
#       builtin echo 'this is a function'
#   }
#
# It will cause syntax error.
#
foo()
{
    builtin echo 'this is a function'
}

foo
-(dearvoid@LinuxEden:Forum)-(~/void/bash)-
[$$=7463 $?=0]
; ./confusing-aliases-2.sh
./confusing-aliases-2.sh: line 17: syntax error near unexpected token `('
./confusing-aliases-2.sh: line 17: `foo()'
-(dearvoid@LinuxEden:Forum)-(~/void/bash)-
[$$=7463 $?=2]
; bye
      
'
梅须逊雪三分白 雪却输梅一段香

TOP

正如 bash 的 manual 所述: The rules concerning the definition and use of aliases are somewhat confusing.       
'
梅须逊雪三分白 雪却输梅一段香

TOP

命令查找时先从alias再到func, 所以。。。      
面包会有的 女人也会有的
_______________________

TOP

好像有个enable命令可以忽略内置命令。      

TOP

发新话题