Differences between revisions 1 and 4 (spanning 3 versions)
Revision 1 as of 2021-08-13 21:29:36
Size: 1478
Editor: GreyCat
Comment: Because.
Revision 4 as of 2021-08-18 12:08:34
Size: 1870
Editor: emanuele6
Comment: add the solution that i came up with when someone asked about quines 4 days ago
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
= Bash quine =
Line 36: Line 37:
This other one consists of a function that uses `declare -f` to print its own definition and the remaining code.

The function's code needs to be written in this precise format and there needs to be a trailing space after `f ()` and `{` to match `declare -f`'s output.
{{{#!highlight bash
#!/bin/bash -
f ()
{
    echo '#!/bin/bash -';
    declare -f f;
    echo f
}
f
}}}
Line 39: Line 54:
CategoryShell CategorySillyThings CategorySillyThings

Bash quine

A quine is a program that takes no input, and prints its own source code as output. Writing one is challenging in any language, and usually involves poking into the darkest, smelliest corners of the syntax.

If you've come across this page through some sort of wandering browsing, you might wish to stop reading after this introduction, and attempt to write a quine yourself. Reading the finished results here is not as educational as the struggle to write one. If on the other hand you've already struggled, either successfully or unsuccessfully, and would like to compare your results against someone else's, then read on.

Invalid quines

The classic shell approach would be something like

   1 #!/bin/sh
   2 cat "$0"

However, this is considered invalid, as it takes input from the file system.

The other classic shell approach would be the empty program. This one is considered to fail the spirit of the challenge, because it doesn't teach you much.

Valid quines

This first one is derived from the Java quine posted on the wikipedia page.

   1 #!/bin/bash
   2 q=(
   3 '#!/bin/bash'
   4 'q=('
   5 ')'
   6 'printf "%s\n" "${q[@]:0:2}"'
   7 'printf "\047%s\047\n" "${q[@]}"'
   8 'printf "%s\n" "${q[@]:2}"'
   9 )
  10 printf "%s\n" "${q[@]:0:2}"
  11 printf "\047%s\047\n" "${q[@]}"
  12 printf "%s\n" "${q[@]:2}"

This other one consists of a function that uses declare -f to print its own definition and the remaining code.

The function's code needs to be written in this precise format and there needs to be a trailing space after f () and { to match declare -f's output.

   1 #!/bin/bash -
   2 f () 
   3 { 
   4     echo '#!/bin/bash -';
   5     declare -f f;
   6     echo f
   7 }
   8 f

(May add more later if I figure them out.)


CategorySillyThings

BashQuine (last edited 2022-07-12 22:52:49 by emanuele6)