简体   繁体   English

如何使用自定义外壳回显$ 0

[英]How to echo $0 with a custom shell

I'm writing a custom shell and echo works with my shell variables: 我正在编写一个自定义外壳,而echo可与我的外壳变量一起使用:

'PATH' is set to /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/local/go/bin.
$ str=FOO
$ echo $str
19163: executing echo
FOO
19163: executed
$ str=BAR
$ echo $str
19170: executing echo
BAR
19170: executed
$ 

The implementation of shell variables looks like: Shell变量的实现如下所示:

static bool expand_parameter(char *shellcommand, hashtable_t *hashtable) {
    char mystring[CMD_LEN];
    char *cp;
    char *ep;
    strcpy(mystring, shellcommand);
    cp = strstr(mystring, "$");
    int position = cp - mystring;
    int quote = isBetweenQuotes(position, mystring);
    if (cp) {
        *cp = '\0';
        strcpy(shellcommand, mystring);
        ep = ++cp;
        while (*ep && (*ep != ' ')) {
            ep++;
        }
        if (!quote)
            strcat(shellcommand, ht_get(hashtable, cp));
        else {
            strcat(shellcommand, "$");
            strcat(shellcommand, cp);
            strcpy(mystring, shellcommand);
            return false;
        }
    }
    strcpy(mystring, shellcommand);
    return true;
}

How should I make the shell print echo $0 that should echo the shell name? 我应该如何使shell打印echo $0应该回显shell名称? Should I just hardcode it into my shell variable function or is there a best practice way to do it? 我应该将其硬编码到我的shell变量函数中,还是有最佳实践呢?

The purpose of the code is to enable shell variables. 该代码的目的是启用外壳程序变量。 The project is https://github.com/montao/openshell 该项目是https://github.com/montao/openshell

Shell parameters, like $0 , $1 ... are received to your shell as the array char **argv passed as second parameter to main() function. Shell参数(例如$0$1 ...)作为数组char **argv作为第二个参数传递到main()函数而接收到您的shell。 If you don't want to touch too much your code, you can copy these variables as keys 0 , 1 ... to the hash table prior to calling your expand_parameter function, and it should work. 如果你不想碰你太多的代码,你可以将这些变量作为密钥复制01 ...哈希表呼唤你之前expand_parameter功能,它应该工作。 But someday you'll have to implement a shift like command and perhaps you'll have to manage them differently. 但是总有一天,您将不得不执行类似shift命令,也许您将不得不以不同的方式来管理它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM