OK I'm attempting to work through the exercises in the Advanced Bash Scripting Guide. In the 'EASY' section (HA HA HA) there's an exercise to write a script that echoes itself to stdout backwards. I'm going on day 3 so I may have strayed horribly off-path and built a monstrosity that's totally unnecessary but I'm almost at the end.
The basic outline of the script logic is to:
1) read each character of the script and assign it to an array element.
2) Figure out the length of the array, then start echoing the characters in reverse order (starting at the end and moving back).
The problem is that since only one character is read (via read -n1), on output a line feed follows each character. If I use 'echo -n' the characters are output as one long string and even the 'true' linefeeds which exist in the script are not echoed.
I can reassemble words with the following ugly kludge:
cat junk | tr '\n' Z | sed 's/ZZ/\n/g' | sed 's/Z//'g
where 'junk' is a file containing each character on a separate line. Any help anybody can offer would be appreciated, so I can move on to the next challenge. Thanks in advance!
Here is the script:
#!/bin/bash
#
# absxm2e4.sh
# -----------
#
# Backwards Listing
#
# Write a script that echoes itself to stdout, but backwards.
#
WORKFILE=/tmp/$(basename $0).work
#BWFILE=$(mktemp)
BWFILE=$HOME/scripts/junk
echo "Temporary file is: $BWFILE"
NEWLINE="\n"
cat $0 > $WORKFILE # Write file to temporary file
exec 3<&0 # Save old stdin file handle
exec 0<$WORKFILE # Set stdin to this file
index=0 # array index
declare -a filearray # declare the character array
# Build filearray by loading each character
while read -n1 c
do
filearray[$index]=$c
let index=index+1
done
echo ${filearray[@]}
echo "The length of the filearray is: ${#filearray[@]}."
arraylen=${#filearray[@]}
# Now build the backwards array
let bwindex=arraylen-1
while [ $bwindex -ge 0 ]
do
echo ${filearray[$bwindex]} >> $BWFILE
let bwindex=bwindex-1 # Decrement array index
done
cat $BWFILE
exec 0<&3 # Restore stdin
exit 0