编程提领/解决在bash别名 [英] Programmatically dereference/resolve aliases in bash

查看:136
本文介绍了编程提领/解决在bash别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要确定哪些命令外壳别名解析为在bash,编程;即,我需要编写,将采取一个名字可能指的是一个别名,并返回真正的bash函数命令,它最终是指,通过别名链递归适用。

I need to determine which command a shell alias resolves to in bash, programmatically; i.e., I need to write a bash function that will take a name potentially referring to an alias and return the "real" command it ultimately refers to, recursing through chains of aliases where applicable.

例如,下面给出的别名:

For example, given the following aliases:

alias dir='list -l'
alias list='ls'

在我的功能就是 dereference_alias

dereference_alias list    # returns "ls"
dereference_alias dir     # also returns "ls"

有一些内置的我不知道,这是否整齐,否则我就辞职自己刮别名

Is there some builtin I don't know about that does this neatly, or shall I resign myself to scraping the output of alias?

推荐答案

下面就是我正在做的,虽然我不知道这是最好的方式:

Here's how I'm doing it, though I'm not sure it's the best way:

dereference_alias () {
  # recursively expand alias, dropping arguments
  # output == input if no alias matches
  local p
  local a="$1"
  if [[ "alias" -eq $(type -t $a) ]] && p=$(alias "$a" 2>&-); then
    dereference_alias $(sed -re "s/alias "$a"='(\S+).*'$/\1/" <<< "$p")
  else
    echo $a
  fi
}

这里主要的缺点是我靠 SED ,和我的别名将任何参数来停止在第一个空间,希望没有别名将永远点一个程序当中,由于某些原因,有空格在其名称(即别名badprogram ='A \\非常\\坏\\程序 - 有些参数的),这是一个合理的足够的假设,但仍。我认为,至少在整个 SED 部分可以通过或许真的杠杆的bash自己的解析/分裂/命令行的标记化所取代,但我不知道从哪里开始。

The major downsides here are that I rely on sed, and my means of dropping any arguments in the alias stops at the first space, expecting that no alias shall ever point to a program which, for some reason, has spaces in its name (i.e. alias badprogram='A\ Very\ Bad\ Program --some-argument'), which is a reasonable enough assumption, but still. I think that at least the whole sed part could be replaced by maybe something leveraging bash's own parsing/splitting/tokenization of command lines, but I wouldn't know where to begin.

这篇关于编程提领/解决在bash别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆