使用源代码将文件的一部分包含在bash脚本中 [英] Using source to include part of a file in a bash script

查看:35
本文介绍了使用源代码将文件的一部分包含在bash脚本中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个bash脚本,需要使用单独文件中包含的一些变量.

I've a bash script that need to use some variables included in a separate file.

通常,为了包括整个文件,我将在主脚本中使用源otherfile.sh.在这种情况下,我只需要使用此文件的一部分.我无法使用(包括)文件其余部分中包含的其余变量.

Normally, for including the entire file I would use source otherfile.sh in the main script. In this case I need to use just a portion of this file. I can't use (include) the rest of the variables included in the rest of the file.

要过滤配置文件的内容(例如,从标记#start"到#end"的示例),我使用awk,但无法将输出重定向到soruce命令.

To filter the content of the config file (let's say just as example from the tag "# start" to "# end") I use awk, but I can't redirect the output to the soruce command.

在我的代码下面:

awk ' /'"# start"'/ {flag=1;next} /'"# end"'/{flag=0} flag { print }' config.sh

您知道将此命令的输出重定向到源代码的任何方法吗?还有其他方法可以在运行时将输出包括在我的bash脚本中吗?

Do you know any way to redirect the output of this command into source? Is there any other way to include the output in my bash script at run-time?

顺便说一句,我不想​​创建临时文件(似乎我太脏了……).我已经尝试了在此站点上找到的内容,但是由于某些原因,它不起作用.下面是我找到的解决方案.

By the way, I wouldn't like to create temporaty files (it seems me too dirty...)..and I've tried something found on this site, but for some reasons it doesn't work. Below there's the solution I've found.

awk ' /'"# start"'/ {flag=1;next} /'"# end"'/{flag=0} flag { print }' config.sh | source /dev/stdin

谢谢

路卡

推荐答案

可以从 bash 中的进程替换中读取:

source can read from a process substitution in bash:

source <( awk ' ... ' config.sh )

sed 提供了一种更简单的方法来获取行的子集:

sed allows a simpler way to get the subset of lines:

sed -n '/#start/,/#end/p' config.sh

更新:看来这只能在 bash 4或更高版本中使用.

UPDATE: It appears that this may only work in bash 4 or later.

这篇关于使用源代码将文件的一部分包含在bash脚本中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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