gpt-4o-2024-05-13· OpenAI
WildChat-4.8M (AI2)
Develop a script that takes a string as an argument and returns its reverse version,…
- User
Develop a script that takes a string as an argument and returns its reverse version, changing uppercase letters to lowercase and back. Examples: ./loops1.sh “Hello World”
DLROw OLLEh
./loops1.sh “bash”
HSAB
- Assistant
Below is a simple
bashscript that takes a string as an argument, reverses it, changes uppercase letters to lowercase and vice versa.#!/bin/bash # Check if exactly one argument was passed if [ "$#" -ne 1 ]; then echo "Usage: $0 <string>" exit 1 fi # Input string input=$1 # Reverse the string and change case reverse="" length=${#input} for (( i=$length-1; i>=0; i-- )) do char="${input:$i:1}" if [[ $char =~ [A-Z] ]]; then reverse+=$(echo "$char" | tr 'A-Z' 'a-z') elif [[ $char =~ [a-z] ]]; then reverse+=$(echo "$char" | tr 'a-z' 'A-Z') else reverse+=$char fi done echo $reverseHow to use the script:
-
Save the script in a file, for example,
loops1.sh. -
Make the script executable by running:
chmod +x loops1.sh -
Run the script with a string argument:
./loops1.sh "Hello World"Output:
DLROw OLLEh./loops1.sh "bash"
-