将脚本的输出作为脚本执行

将脚本的输出作为脚本执行

本文介绍了bash:将脚本的输出作为脚本执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个简单的脚本来生成给定长度(例如10)的a和b的所有组合.我希望能够在命令行上执行此操作(我知道如果将所有内容都放入bash脚本文件中并执行它,这相当容易).但是,我想知道是否可以在没有任何额外文件的情况下进行操作.这是我到目前为止的内容:

I'm writing a simple script to generate all combinations of a and b of a given length (say 10). I want to be able to do this on a command line (I know this is fairly easy if I just put everything in a bash script file and execute it). However, I was wondering if it's possible to do without any extra files. Here's what I have so far:

n=10;
for i in `seq 1 1 $n`; do
    echo "for a$i in {a..b}; do ";
done;
echo -n "echo ";
for i in `seq 1 1 $n`; do
    echo -n '$'"a$i"; done;
    echo;
for i in `seq 1 1 $n`; do
    echo "done;";
done

(我对代码进行了格式化以提高可读性,但实际上所有内容都在提示符下一行显示)

(I formatted the code for readability, but it's actually all on one line run from a prompt)

这给了我以下输出:

for a1 in {a..b}; do
for a2 in {a..b}; do
for a3 in {a..b}; do
for a4 in {a..b}; do
for a5 in {a..b}; do
for a6 in {a..b}; do
for a7 in {a..b}; do
for a8 in {a..b}; do
for a9 in {a..b}; do
for a10 in {a..b}; do
echo $a1$a2$a3$a4$a5$a6$a7$a8$a9$a10
done;
done;
done;
done;
done;
done;
done;
done;
done;
done;

这很好.如果我将其复制并粘贴回命令行,它将像超级按钮一样工作,并为我提供结果.

which is just fine. If I copy that and paste it back on the command line, it works like a charm and gives me the result.

问题是我该如何仅使用初始脚本来执行此操作,而不进行复制粘贴并且不将任何内容重定向到文件.

The question is how do I do this with just the initial script, without copy-pasting and without redirecting anything to files.

我曾尝试在脚本周围粘贴$(),但这使我找不到'for'命令'",因为它实际上不是命令,而是内置的bash.在此之前,我曾尝试将eval放在某处,但我只会不断收到更多错误.我有点受阻,因此不胜感激.

I've tried sticking $( ) around the script, but that gives me "No command 'for' found'", since it's not really a command but a bash builtin. I've tried putting eval somewhere before this, but I just keep getting more errors. I'm a bit stuck, so any help would be greatly appreciated.

(顺便说一句,重申一下,我正在或多或少地这样做,只是为了学习更多的bash,这就是为什么我不想将输出重定向到文件然后执行该文件.我知道该怎么做那部分,但我不知道如何从命令行执行该操作

(Btw, just to reiterate, I'm doing this more or less to just learn bash more -- that's why I don't want to redirect the output to a file and then execute that file. I know how to do that part, but I don't know how to just do it from command line)

推荐答案

您需要使用一个eval,$()为您提供一个字符串.

You need to use an eval, $() gives you a string.

eval $( echo echo foo )

另一种选择是插入子外壳并将其通过管道传递给bash:

Another option is to stick into a subshell and pipe it to a bash:

(echo echo foo) | /bin/bash

这篇关于bash:将脚本的输出作为脚本执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 19:26