Skip to content
The Chat Archive
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,…

  1. 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

    ./loops1.sh “EPAM”

    mape

  2. Assistant

    Certainly! Below is a bash script that takes a string as an argument, reverses it, and swaps the case of each character:

    #!/bin/bash
    
    if [ -z "$1" ]; then
      echo "Please provide a string as an argument."
      exit 1
    fi
    
    input_string="$1"
    reversed_string=""
    
    # Loop from the end of the string to the beginning
    for (( i=${#input_string}-1; i>=0; i-- )); do
      char="${input_string:i:1}"
      
      # Check if the character is lowercase
      if [[ "$char" =~ [a-z] ]]; then
        # Convert lowercase to uppercase
        reversed_string+="${char^}"
      elif [[ "$char" =~ [A-Z] ]]; then
        # Convert uppercase to lowercase
        reversed_string+="${char,}"
      else
        # Add non-alphabetic characters as they are
        reversed_string+="$char"
      fi
    done
    
    echo "$reversed_string"
    

    To use this script:

    1. Save it as loops1.sh.
    2. Give it execute permissions with the command chmod +x loops1.sh.
    3. Run the script with a string argument, for example:
      ./loops1.sh "Hello World"
      ./loops1.sh "bash"
      ./loops1.sh "EPAM"
      

    The script will output the expected results:

    DLROw OLLEh
    HSAB
    mape