如何在fish shell脚本中使用命令行参数

时间:2015-07-16 18:33:37

标签: shell fish

我试图为grep写一个别名:

# config.fish
alias grepcustom="grep -r $argv ~/"

基本上我想要做的就是在我的主目录上使用递归grep而不必输入任何内容(我知道我很懒)。

当我重新启动shell并运行grepcustom时,我得到:

$ grepcustom "hello"
grep: hello: No such file or directory

有一个包含" hello"的文件。如果我在shell中运行grep -r它可以正常工作。但是,问题似乎在于我的别名如何识别命令行参数" hello"。我做错了什么?

2 个答案:

答案 0 :(得分:7)

你需要写一个实际的函数:

$ alias grepcustom="grep -r $argv ~/"
$ type grepcustom
grepcustom is a function with definition
function grepcustom
    grep -r  ~/ $argv;
end

那里发生了什么?由于我没有在我的shell中定义$argv,它被一个空字符串替换,然后alias添加了$ argv以使该函数有效。让我们试试单引号:

$ alias grepcustom='grep -r $argv ~/'
$ type grepcustom
grepcustom is a function with definition
function grepcustom
    grep -r $argv ~/ $argv;
end

这显然不对。你想要

function grepcustom -a pattern
    grep -r $pattern ~/
end

答案 1 :(得分:0)

我不知道鱼只有两件事。

  1. $args变量可能已在您的别名中展开。

    运行alias grepcustom或任何fish命令显示别名的值,您应该看到。您希望在别名定义上使用单引号。

  2. 除非fish支持您在别名(而不是正常位置)中手动放置$argv,否则这不起作用,因为别名在别名扩展后放置参数。你需要一个功能。

相关问题