通常,bash可以分配命令的多行输出:
L=`ls`
这适用于交互式外壳程序和脚本。但是似乎内置变量的输出无法捕获到变量中:
L=`dirs -l -p`
这在交互式外壳中有效,但是在脚本中,只有第一行以变量结尾,这可能是由于bash对内建函数的不同处理。
为什么会发生这种情况,我该怎么做呢?
您的提问方式似乎有些含糊。你说:
但是在脚本中,只有第一行以变量结尾
然后您的注释表明您正在编写Shell函数-而不是脚本。
我怀疑您知道脚本对于更改目录是无用的,因为cd
脚本中的任何内容都不会传播到高级Shell。如果确实要在脚本中开发目录更改器,那么您将很难过,因为目录堆栈不会被从属shell继承:
$ dirs -l
/home/msw /home/msw/Ubuntu One /home/msw /usr/bin /usr/local /bin /usr/local
$ cat > dirs.sh
dirs -l
$ bash dirs.sh
/home/msw
您可以使用一个函数来帮助您:
$ function passdirs() { bash ndirs.sh `dirs -l -p`; }
$ cat > ndirs.sh
echo $#
echo "$@"
$ passdirs
8
/home/msw /usr/local /usr/bin /bin /usr/local /usr/bin /bin /home/msw
但是,当然,您还需要该函数cd
在当前shell中生效,在这种情况下,通过命令行进行包装和展开参数是一个引号,因此最好在该函数中完成所有操作
$ function cd_pattern() {
cd $(dirs -l -p | grep --max-count=1 -e "$1") ; dirs
}
$ dirs
~ /usr/local /bin /usr/share/doc/evince ~/Ubuntu One
$ cd_pattern v..c
/usr/share/doc/evince /usr/local /bin /usr/share/doc/evince ~/Ubuntu One
后者也改用$(...)
反引号作为同义词,以减少报价混乱。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句