Chinaunix

标题: bash下alias快捷键请教 [打印本页]

作者: weichanghe2000    时间: 2015-12-05 23:59
标题: bash下alias快捷键请教
本帖最后由 weichanghe2000 于 2015-12-06 14:12 编辑

大家好,刚学习bash一会儿,碰到个问题。
能够帮忙解答下吗?

我做了一个快捷键 alias open="cd /tmp/res/$1 && ls",
当我用open math时,目的是 进去文件夹 /tmp/res/math,然后执行 ls。
但是最后发现, pwd 还是 /tmp/res,不是 /tmp/res/math。

不知道哪里出错了。
麻烦指点下,多谢。


作者: songyc_2015    时间: 2015-12-06 16:05
用函数吧,
$ cdls()
{
    cd /tmp/res/$1 && ls
}
$ alias open='cdls'
$ open math
作者: weichanghe2000    时间: 2015-12-06 21:06
回复 2# songyc_2015

你好,这个是可以,谢谢。
主要是我不知道我的问题,错在哪里,
一直没有想明白。


   
作者: lgfang    时间: 2015-12-07 09:34
本帖最后由 lgfang 于 2015-12-07 09:37 编辑

一般来说,双引号里的 $xxx 会被立即展开。所以  alias open="cd /tmp/res/$1 && ls" ==》 alias open="cd /tmp/res/ && ls"。
解决办法:双引号改成单引号就可以。

但是 刚才在bash4里试了下,单引号双引号都可以 .
作者: weichanghe2000    时间: 2015-12-07 21:33
回复 4# lgfang

我的改成了单引号也不行。没有进入/tmp/res/math


不知道为什么?

   
作者: jcdiy0601    时间: 2015-12-08 10:00
在centos6上面试过了,单双引号都是可以的,估计是版本问题
要是想永久生效,建议写入/etc/profile中,用二楼函数的方法写入文件,然后source /etc/profile生效
作者: lgfang    时间: 2015-12-08 18:30
本帖最后由 lgfang 于 2015-12-17 10:30 编辑

回复 5# weichanghe2000

sorry, 当时有点晕,应该单双引号都不行。因为 alias 原本就不支持参数(我之前说"bash4可以"是我测试得不对)

Bash manual:

   There is no mechanism for using arguments in the replacement text,
as in `csh'.  If arguments are needed, a shell function should be used
(see Shell Functions).


   
作者: weichanghe2000    时间: 2015-12-10 21:10
回复 7# lgfang


    非常感谢你提供的官方的Manual。
多谢。




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2