sli*_*lik 118 bash shell .bash-profile
是否可以执行以下操作:
我想运行以下内容:
mongodb bin/mongod
Run Code Online (Sandbox Code Playgroud)
在我的bash_profile中我有
alias = "./path/to/mongodb/$1"
Run Code Online (Sandbox Code Playgroud)
Pau*_*ce. 219
别名将扩展为它所代表的字符串.别名之后的任何内容都将在其扩展后出现,而不需要或能够作为显式参数传递(例如$1).
$ alias foo='/path/to/bar'
$ foo some args
Run Code Online (Sandbox Code Playgroud)
将扩大到
$ /path/to/bar some args
Run Code Online (Sandbox Code Playgroud)
如果要使用显式参数,则需要使用函数
$ foo () { /path/to/bar "$@" fixed args; }
$ foo abc 123
Run Code Online (Sandbox Code Playgroud)
将被执行,就像你已经完成
$ /path/to/bar abc 123 fixed args
Run Code Online (Sandbox Code Playgroud)
要取消定义别名:
unalias foo
Run Code Online (Sandbox Code Playgroud)
要取消定义函数:
unset -f foo
Run Code Online (Sandbox Code Playgroud)
要查看类型和定义(对于每个已定义的别名,关键字,函数,内置或可执行文件):
type -a foo
Run Code Online (Sandbox Code Playgroud)
或仅键入(对于最高优先级发生):
type -t foo
Run Code Online (Sandbox Code Playgroud)
lee*_*25d 22
通常,当我想参数传递给在猛砸别名,我用一个别名,像这样的功能,例如组合:
function __t2d {
if [ "$1x" != 'x' ]; then
date -d "@$1"
fi
}
alias t2d='__t2d'
Run Code Online (Sandbox Code Playgroud)
osi*_*hra 19
要使用别名中的参数,我使用此方法:
alias myalias='function __myalias() { echo "Hello $*"; unset -f __myalias; }; __myalias'
Run Code Online (Sandbox Code Playgroud)
它是一个包含在别名中的自毁函数,因此它几乎是两个世界中最好的,并且不会在你的定义中占用额外的一行...我讨厌,哦是的,如果你需要那个回报值,你必须在调用unset之前存储它,然后在那个自毁函数中使用"return"关键字返回值:
alias myalias='function __myalias() { echo "Hello $*"; myresult=$?; unset -f __myalias; return $myresult; }; __myalias'
Run Code Online (Sandbox Code Playgroud)
所以..
你可以,如果你需要在那里有变量
alias mongodb='function __mongodb() { ./path/to/mongodb/$1; unset -f __mongodb; }; __mongodb'
Run Code Online (Sandbox Code Playgroud)
当然...
alias mongodb='./path/to/mongodb/'
Run Code Online (Sandbox Code Playgroud)
实际上会做同样的事情而不需要参数,但就像我说的,如果你因为某些原因想要或需要它们(例如,你需要2美元而不是1美元),你需要使用这样的包装器.如果它大于一行你可能会考虑直接写一个函数,因为随着它变得越来越大,它会变得越来越像.函数很棒,因为你获得了函数给出的所有特权(参见bash手册页中函数可以提供的好东西的完成,陷阱,绑定等).
我希望能帮助你:)
小智 8
这是可以避免使用功能的解决方案:
alias addone='{ num=$(cat -); echo "input: $num"; echo "result:$(($num+1))"; }<<<'
Run Code Online (Sandbox Code Playgroud)
测试结果
addone 200
input: 200
result:201
Run Code Online (Sandbox Code Playgroud)
在csh(而不是bash)中,您可以完全按照您的意愿进行操作。
alias print 'lpr \!^ -Pps5'
print memo.txt
Run Code Online (Sandbox Code Playgroud)
该符号\!^导致此时将参数插入到命令中。
该!字符前面带有 a,\以防止将其解释为历史命令。
您还可以传递多个参数:
alias print 'lpr \!* -Pps5'
print part1.ps glossary.ps figure.ps
Run Code Online (Sandbox Code Playgroud)
(示例取自http://unixhelp.ed.ac.uk/shell/alias_csh2.1.html。)