通常我有一个.bashrc文件,其中ll别名设置为
alias ll='ls -l'
当我ll
手动调用时,它可以正常工作。但是,有时我可能需要从字符串运行命令。所以我想运行:
COMMAND="ll"
bash --login -c "$COMMAND"
不幸的是,这会抱怨找不到ll命令并失败。如果我检查别名,它确实是在此范围内定义的,我将检查如下:
COMMAND="alias"
bash --login -c "$COMMAND"
上面提到的正确打印了我所有的别名。
有什么方法可以在bash的-c command_string参数中使用别名命令?
这里要注意几件事,首先是关于使用该--login
选项的运行:
When bash is invoked as an interactive login shell, or as a non-inter‐
active shell with the --login option, it first reads and executes com‐
mands from the file /etc/profile, if that file exists. After reading
that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile,
in that order, and reads and executes commands from the first one that
exists and is readable.
因此,此命令不会读取您的.bashrc
。其次,别名仅在交互式外壳程序中有效,因此即使该别名已获得,在您的命令中也将不起作用。但是,功能确实可以在非交互式外壳中工作。因此,您应该将别名转换为函数,并通过上述方法之一将其用作源~/.bash_profile
。
或者,您可以将当前环境中定义的函数导出到继承的函数bash -c
。我有这个功能:
adrian@adrian:~$ type fn
fn is a function
fn ()
{
find . -name "$1"
}
我可以在这样的子shell中调用它:
adrian@adrian:~$ export -f fn
adrian@adrian:~$ bash -c "fn foo*"
./foo.bar
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句