Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-05-13· OpenAIAi2 WildChat-4.8M (AI2)

Develop a bash script that takes a string as an argument and returns its reverse…

  1. User

    Develop a bash script that takes a string as an argument and returns its reverse version, changing uppercase letters to lowercase and back

  2. Assistant

    Certainly! Below is a bash script that takes a string as an argument, reverses it, and changes uppercase letters to lowercase and lowercase letters to uppercase.

    Save it as reverse_string.sh:

    #!/bin/bash
    
    # Check if an argument is provided
    if [ -z "$1" ]; then
      echo "Usage: $0 <string>"
      exit 1
    fi
    
    # Input string
    input_string="$1"
    
    # Reverse the string and swap case
    reversed_string=$(echo "$input_string" | rev | tr '[:upper:][:lower:]' '[:lower:][:upper:]')
    
    # Output the result
    echo "$reversed_string"
    

    How to Use:

    1. Save the script to a file named reverse_string.sh.
    2. Make the file executable by running the following command: chmod +x reverse_string.sh.
    3. Run the script with a string argument: ./reverse_string.sh "YourStringHere".

    Example:

    ./reverse_string.sh "HelloWorld"
    

    Output:

    DLROwOLLEH
    

    In this script:

    • if [ -z "$1" ];: Checks if the script received an argument.
    • input_string="$1": Assigns the input argument to input_string.
    • reversed_string=$(echo "$input_string" | rev | tr '[:upper:][:lower:]' '[:lower:][:upper:]'):
      • echo "$input_string": Outputs the input string.
      • rev: Reverses the string.
      • tr '[:upper:][:lower:]' '[:lower:][:upper:]': Swaps the case for the characters in the reversed string.
    • echo "$reversed_string": Outputs the final reversed and case-swapped string.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.