| 1 | #!/bin/bash |
| 2 | # script-array.sh: Loads this script into an array. |
| 3 | # Inspired by an e-mail from Chris Martin (thanks!). |
| 4 | |
| 5 | script_contents=( $(cat "$0") ) # Stores contents of this script ($0) |
| 6 | #+ in an array. |
| 7 | |
| 8 | for element in $(seq 0 $((${#script_contents[@]} - 1))) |
| 9 | do # ${#script_contents[@]} |
| 10 | #+ gives number of elements in the array. |
| 11 | # |
| 12 | # Question: |
| 13 | # Why is seq 0 necessary? |
| 14 | # Try changing it to seq 1. |
| 15 | echo -n "${script_contents[$element]}" |
| 16 | # List each field of this script on a single line. |
| 17 | # echo -n "${script_contents[element]}" also works because of ${ ... }. |
| 18 | echo -n " -- " # Use " -- " as a field separator. |
| 19 | done |
| 20 | |
| 21 | echo |
| 22 | |
| 23 | exit 0 |
| 24 | |
| 25 | # Exercise: |
| 26 | # -------- |
| 27 | # Modify this script so it lists itself |
| 28 | #+ in its original format, |
| 29 | #+ complete with whitespace, line breaks, etc. |