Bash Script Rotation Cipher
Solution 1:
Conversion to upper case can be done in Bash using:
TEXT="foobar"
echo ${TEXT^^}
A rotation cipher could be implemented using tr
, e.g rot13:
echo $TEXT | tr 'A-Za-z' 'N-ZA-Mn-za-m'
# sbbone
rot5 would look like this:
echo $TEXT | tr 'A-Za-z' 'F-ZA-Ef-za-e'
# kttgfw
A partial version without tr
command:
#!/bin/bash
TEXT="AZ"
for (( i=0; i<${#TEXT}; i++ )); do
printf "%s -> %d\\n" "${TEXT:$i:1}" \'${TEXT:$i:1}
printf -v val "%d" \'${TEXT:$i:1}
shifted=$(($val + 5))
echo "shifted: $shifted"
printf "\\$(printf '%03o' $shifted)\n"
# A-Z is in range:
# 65-90
if [[ $shifted -gt 90 ]];then
# if value is greated than Z letter you need to subtrack 26
# so that 91 would become letter A
echo "$shifted val too large"
corrected=$(( $shifted - 26))
echo "corrected ord value $corrected"
printf "\\$(printf '%03o' $corrected)\n"
fi
done
the output should look like:
A -> 65
shifted: 70
F
Z -> 90
shifted: 95
_
95 val too large
corrected ord value 69
E
The script converts letters to its corresponding ASCII codes, performs shift and converts codes back to letters. You need to make sure that it works for uppper and lower case letters (or support only one of them). I'll leave the rest as an exercise for the kind reader.