Bash: executing script output as a script

I am writing a simple script to create all combinations of a and b of a given length (say 10). I want to be able to do this on the command line (I know this is pretty easy if I just put everything in a bash script file and executed it). However, I was wondering if additional files could be dispensed with. Here is what I still have:

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 actually everything on the same line starts from the prompt)

This gives me the following result:

 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 great. If I copy this and bring it back to the command line, it will work like a charm and give me the result.

The question is, how can I do this only with the initial script, without copying and without redirecting anything to files.

I tried sticking $ () around the script, but this gives me "No command" for the "found", as this is not a real command, but a built-in bash. I tried to put eval somewhere before that, but I just keep getting more errors. I'm a little stuck, so any help would be greatly appreciated.

(By the way, I’ll just repeat, I’m doing it more or less just to find out more bash - why I don’t want to redirect the output to a file and then execute this file. I know how to execute this part, but I don’t know how it is make from the command line)

+4
source share
2 answers

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

 eval $( echo echo foo ) 

Another option is to paste into a subshell and pass it to bash:

 (echo echo foo) | /bin/bash 
+13
source

You can do for i in $(seq $n) instead of seq 1 1 $n .

You can do for ((i=1; i<=$n; i++)) and avoid calling an external utility.

You can do this (hack only one loop slightly):

 $ a=A; b=B; n=4; s=''; for ((i=1;i<=n;i++)); do s+="{$a..$b}"; done; eval echo "''" $s"$'\n'" 

or this (strongly hacker without any cycles ):

 $ a=A; b=B; n=4; eval echo "''" $(printf "{$a..$b}%.0s" $(eval echo "{1..$n}"))"$'\n'" 

Or you will get this:

  AAAA AAAB AABA AABB ABAA ABAB ABBA ABBB BAAA BAAB BABA BABB BBAA BBAB BBBA BBBB 
+2
source

Source: https://habr.com/ru/post/1339999/


All Articles