Last active
January 25, 2019 16:06
-
-
Save 75th/5778694 to your computer and use it in GitHub Desktop.
A Bash script for Caesar ciphers. I needed (well, wanted) a tool to do ROT-n ciphers for arbitrary n. So here it is. If n is not provided, it defaults to ROT-13. No ROT-5 for numerals as yet. This is my first shell script for public consumption; feedback is eagerly welcome, but please be gentle.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /bin/bash | |
# Usage: rot [base] string | |
# | |
# Base is assumed to be 13 if not specified. | |
# | |
# Bases not in 0-25 are taken modulo 26; negatives are increased by | |
# 26es until they're positive. Thus, any integer should work | |
# as expected. | |
function rot() { | |
local pattern='^-?[0-9]+$' | |
if [[ $1 =~ $pattern ]]; # Is first argument an integer? | |
then | |
local base="$1" | |
local string="$2" | |
local origbase="$1" # Save original base for later clarification | |
else | |
local base="13" | |
local string="$1" | |
local origbase="null" | |
fi | |
while (($base < 0)) | |
do | |
base=$(($base + 26)) # Modulo ought to work this way | |
done | |
local realbase=$(($base % 26)) | |
local rot0='A-Za-z' | |
local rot1='B-ZAb-za' | |
local rot2='C-ZA-Bc-za-b' | |
local rot3='D-ZA-Cd-za-c' | |
local rot4='E-ZA-De-za-d' | |
local rot5='F-ZA-Ef-za-e' | |
local rot6='G-ZA-Fg-za-f' | |
local rot7='H-ZA-Gh-za-g' | |
local rot8='I-ZA-Hi-za-h' | |
local rot9='J-ZA-Ij-za-i' | |
local rot10='K-ZA-Jk-za-j' | |
local rot11='L-ZA-Kl-za-k' | |
local rot12='M-ZA-Lm-za-l' | |
local rot13='N-ZA-Mn-za-m' | |
local rot14='O-ZA-No-za-n' | |
local rot15='P-ZA-Op-za-o' | |
local rot16='Q-ZA-Pq-za-p' | |
local rot17='R-ZA-Qr-za-q' | |
local rot18='S-ZA-Rs-za-r' | |
local rot19='T-ZA-St-za-s' | |
local rot20='U-ZA-Tu-za-t' | |
local rot21='V-ZA-Uv-za-u' | |
local rot22='W-ZA-Vw-za-v' | |
local rot23='X-ZA-Wx-za-w' | |
local rot24='Y-ZA-Xy-za-x' | |
local rot25='ZA-Yza-y' | |
local funcname="rot${realbase}" | |
# If the base was converted above, send the actual 0-25 base to stderr | |
if (($origbase != $realbase)) | |
then | |
echo "(ROT-${realbase})" 1>&2 | |
fi | |
echo "$string" | tr 'A-Za-z' "${!funcname}" | |
} | |
rot "$1" "$2" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment