Linux bash 中带有变量的别名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4438147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:59:39  来源:igfitidea点击:

Alias with variable in bash

linuxbash

提问by Deepank Gupta

I want to create an alias in bashlike this:

我想像这样创建一个别名bash

alias tail_ls="ls -l  | tail"

Thus, if somebody types:

因此,如果有人输入:

tail_ls /etc/ 

it will only show the last 10 files in the directory.

它只会显示目录中的最后 10 个文件。

But $1does not seem to work for me. Is there any way I can introduce variables in bash.

$1似乎对我不起作用。有什么办法可以在bash中引入变量。

采纳答案by Maxim Sloyko

I'd create a function for that, rather than alias, and then exported it, like this:

我会为此创建一个函数,而不是别名,然后将其导出,如下所示:

function tail_ls { ls -l "" | tail; }

export -f tail_ls

Note -fswitch to export: it tells it that you are exporting a function. Put this in your .bashrcand you are good to go.

注意-f切换到export:它告诉它您正在导出一个函数。把它放在你的.bashrc身上,你就可以开始了。

回答by l0b0

tail_ls() { ls -l "$1" | tail; }

tail_ls() { ls -l "$1" | tail; }

回答by jruzafa

The solution of @maxim-sloyko did not work, but if the following:

@maxim-sloyko 的解决方案不起作用,但如果出现以下情况:

  1. In ~/.bashrc add:

    sendpic () { scp "$@" [email protected]:/www/misc/Pictures/; }
    
  2. Save the file and reload

    $ source ~/.bashrc
    
  3. And execute:

    $ sendpic filename.jpg
    
  1. 在 ~/.bashrc 添加:

    sendpic () { scp "$@" [email protected]:/www/misc/Pictures/; }
    
  2. 保存文件并重新加载

    $ source ~/.bashrc
    
  3. 并执行:

    $ sendpic filename.jpg
    

original source: http://www.linuxhowtos.org/Tips%20and%20Tricks/command_aliases.htm

原始来源:http: //www.linuxhowtos.org/Tips%20and%20Tricks/command_aliases.htm

回答by innovati

If you are using the Fish shell (from http://fishshell.com) instead of bash, they write functions a little differently.

如果您使用的是 Fish shell(来自http://fishshell.com)而不是 bash,则它们编写的函数略有不同。

You'll want to add something like this to your ~/.config/fish/config.fishwhich is the equivalent of your ~/.bashrc

你会想要添加这样的东西到你~/.config/fish/config.fish的相当于你的~/.bashrc

function tail_ls
  ls -l  | tail
end

回答by Javier López

alias tail_ls='_tail_ls() { ls -l "" | tail ;}; _tail_ls'

回答by J. Chomel

You can define $1with set, then use your alias as intended:

您可以定义$1with set,然后按预期使用您的别名:

$ alias tail_ls='ls -l "" | tail'
$ set mydir
$ tail_ls