Untitled
unknown
sh
a year ago
2.0 kB
6
Indexable
#!/bin/bash encode() { text=$1 shift=$2 result="" for (( i=0; i<${#text}; i++ )); do char="${text:$i:1}" if [[ "$char" =~ [A-Za-z] ]]; then ascii_val=$(printf '%d' "'$char") ((ascii_val += shift)) if [[ "$char" =~ [a-z] && $ascii_val -gt 122 ]]; then ((ascii_val -= 26)) elif [[ "$char" =~ [A-Z] && $ascii_val -gt 90 ]]; then ((ascii_val -= 26)) fi result+="$(printf "\\$(printf '%03o' "$ascii_val")")" else result+="$char" fi done echo "$result" } decode() { text=$1 shift=$2 encode "$text" "$((0 - shift))" } validate_text() { text=$1 if [[ ! "$text" =~ ^[A-Za-z[:space:][:punct:][:digit:]]+$ ]]; then echo "Error: Input text contains invalid characters." exit 1 fi } validate_shift() { shift=$1 if [[ ! "$shift" =~ ^[1-9]$|^1[0-9]$|^2[0-5]$ ]]; then echo "Error: Shift value must be a positive integer within the range 1-25." exit 1 fi } get_user_input() { read -p "Enter text to $1: " user_text validate_text "$user_text" read -p "Enter shift value (1-25): " shift_value validate_shift "$shift_value" if [ "$1" == "encode" ]; then result=$(encode "$user_text" "$shift_value") echo "Encoded text: $result" elif [ "$1" == "decode" ]; then result=$(decode "$user_text" "$shift_value") echo "Decoded text: $result" fi } if [ "$#" -ne 1 ]; then echo "Usage: $0 [-e | -d]" exit 1 fi if [ "$#" -ne 1 ]; then echo "Usage: $0 [-e | -d]" exit 1 fi case $1 in "-e") get_user_input "encode" ;; "-d") get_user_input "decode" ;; *) echo "Invalid option. Use '-e' to encode or '-d' to decode." exit 1 ;; esac
Editor is loading...
Leave a Comment