0

我正在尝试制作自己的 if 函数,它的编写方式与传统的 if 函数略有不同。

这就是我目前拥有的(可能距离完成还很远)

function check
{
    if [ "$2" = "=" ]; then
        if [ "$1" = "$3" ]; then
            // Don't know what to put in here
        elif [ "$1" != "$3" ]; then
            // Don't know what to put in here
        fi
    elif [ "$2" = "!=" ]; then
        if [ "$1" != "$3" ]; then
            // Don't know what to put in here
        elif [ "$1" = "$3" ]; then
            // Don't know what to put in here   
        fi
    fi
}

完成后,它应该像这样运行:

check $foo != 2
    //do this
end

我如何实现这一目标?

如何合并缩进代码?以及如何合并“结束”语句?

4

2 回答 2

1

听起来你想做的事情最好通过替换testaka[而不是if本身来完成。以下是您完成功能的方式:

function check
{
    if [ "$2" = "=" ]; then
        if [ "$1" = "$3" ]; then
            return 0
        else 
            return 1
        fi
    elif [ "$2" = "!=" ]; then
        if [ "$1" != "$3" ]; then
            return 0
        else
            return 1
        fi
    fi
    echo "Unknown operator: $2" >&2
    return 1
}

以下是如何使用它:

if check "foo" != "bar"
then
    echo "it works"
fi
于 2013-11-11T20:08:06.437 回答
0

你永远不会成功地在 bash 中为if. 这是因为if它是一个 shell 关键字。

关键字保留字、标记或运算符。关键字对 shell 具有特殊意义,并且确实是 shell 语法的构建块。例如,如果对于、做和是关键字。与builtin类似,关键字被硬编码到 Bash 中,但与 builtin不同的是,关键字本身不是命令,而是命令结构的子单元

这是一个演示:

$ type if
if is a shell keyword
$ function if { echo "something"; }
$ type if
if is a shell keyword
$ #so, 'if' has remained a shell keyword
$ #and the new created function 'if' will never work :(
$ type cd
cd is a shell builtin
$ function cd { echo "something"; }
$ type cd
cd is a function
cd () 
{ 
    echo "something"
}
$ cd $HOME
something
$ #so, 'cd' is not anymore a builtin and the new created function 'cd' works! :)
于 2013-11-11T19:25:12.257 回答