linux - 如何使用 bash 获取字符串中函数的内容?

标签 linux bash shell scripting command

我已经搜索过这个特定问题,但找不到任何有用的信息。

假设我在 ~/.bashrc 中定义了以下函数(注意:这是伪代码!):

ANDROID_PLATFORM_ROOT="/home/simao/xos/src/"

function getPlatformPath() {
  echo "$ANDROID_PLATFORM_ROOT"
}

function addCaf() {
  # Me doing stuff
  echo "blah/$(getPlatformPath)"
}

function addAosp() {
  # Me doing stuff
  echo "aosp/$(getPlatformPath)"
}

function addXos() {
  # Me doing stuff
  echo "xos/$(getPlatformPath)"
}

function addAllAll() {
  cd $(gettop)
  # repo forall -c "addCaf; addAosp; addXos" # Does not work!
  repo forall -c # Here is where I need all those commands
}

我的问题:

我需要在一行中获取函数 addCafaddAospaddXos

就像您可以在 bash 中运行以下(伪代码):

这样做;去做;做另一件事; trythis && succeedsdothis ||没有成功;废话

我想在 addCafaddAospaddXos 这三个函数中运行所有命令 在一行中.

感谢任何帮助。

我已经尝试过的:

repo forall -c "bash -c\"source ~/.bashrc; addAllAll\""

但这并没有奏效。

编辑:

阐明我的意思。

我想要这样的结果:

repo forall -c 'function getPlatformPath() { echo "$ANDROID_PLATFORM_ROOT"; }; ANDROID_PLATFORM_ROOT="/home/simao/xos/src/"; echo "blah/$(getPlatformPath)"; echo "aosp/$(getPlatformPath)"; echo "xos/$(getPlatformPath)"'

但我不想手动编写。相反,我想从已经存在的函数中获取这些行。

最佳答案

您可以使用 type 然后解析其输出以对代码行执行任何您想执行的操作。

$ foo() {
> echo foo
> }

$ type foo
foo is a function
foo () 
{ 
    echo foo
}

也许这个例子让事情更清楚:

#!/bin/bash

foo() {
    echo "foo"
}

bar() {
    echo "bar"
}

export IFS=$'\n'

for f in foo bar; do
    for i in $(type $f | head -n-1 | tail -n+4); do
        eval $i
    done
done

exit 0

它是这样的:

$ ./funcs.sh 
foo
bar

脚本所做的是首先遍历您拥有的所有函数(在本例中只有 foo 和 bar)。对于每个函数,它循环遍历该函数的代码(跳过 type 输出中无用的行)并执行它们。所以最后它和拥有这段代码是一样的......

echo "foo"
echo "bar"

...这些正是函数内部的代码行,您正在一个接一个地执行它们。

请注意,您还可以构建一个字符串变量,其中包含由 ; 分隔的所有代码行,如果您不是在每一行上运行 eval,而是执行以下操作:

code_lines=

for f in foo bar; do
        for i in $(type $f | head -n-1 | tail -n+4); do
                if [ -z $code_lines ]; then
                        code_lines="$i"
                else
                        code_lines="${code_lines}; $i"
                fi  
        done
done

eval $code_lines

关于linux - 如何使用 bash 获取字符串中函数的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38741059/

相关文章:

linux - linux下将文件从一个路径复制到另一个路径

c - 内存映射内核空间的解剖结构

linux - 用于测试输出并创建新的继续名称的 Shell 脚本

linux - 无法使用 Firefox-Copper 插件将 CoAP 消息发送到本地地址以外的地址 (::1)

bash - 您如何一遍又一遍地在bash中运行命令直到成功?

perl - 如何获取 Perl 脚本的输出?

linux - 我可以在 Windows 版 GitBash 上使用 Linux 命令吗

bash - 根据系统变量动态设置 cron 作业的时间

linux - 脚本在命令行中工作正常,但在 crontab 中工作不正常

regex - Bash 脚本解析文件以查找模式之间多次出现的字符串