gpt-4o-2024-05-13· OpenAI
WildChat-4.8M (AI2)
Develop a script in bash that takes the temperature value in Celsius OR Kelvins and…
- User
Develop a script in bash that takes the temperature value in Celsius OR Kelvins and returns the inverse value. The formula is pretty simple: C = K - 273; K = C + 273. It should return a single line with no spaces, like: ./temp.sh 122K -> -151C
- Assistant
Sure, here's a simple Bash script to accomplish this. Save the script as
temp.shand make sure it's executable (chmod +x temp.sh).bash#!/bin/bash if [ $# -ne 1 ]; then echo "Usage: $0 <temperature>" exit 1 fi input=$1 if [[ $input == *K ]]; then # Strip the 'K' character temperature=${input%K} # Convert Kelvin to Celsius result=$((temperature - 273)) echo "${result}C" elif [[ $input == *C ]]; then # Strip the 'C' character temperature=${input%C} # Convert Celsius to Kelvin result=$((temperature + 273)) echo "${result}K" else echo "Invalid input. Please provide temperature in the format '122K' or '49C'." exit 1 fiExample usage:
bash$ ./temp.sh 122K -151C $ ./temp.sh 49C 322KExplanation:
-
Input Check:
- The script first checks if the correct number of arguments is passed. If not, it prints the usage message and exits.
-
Determining the Format:
- It checks whether the input string ends with 'K' for Kelvin or 'C' for Celsius using Bash string manipulation.
-
Temperature Conversion:
- If the input is in Kelvin, it strips the 'K' character and converts the remaining number to Celsius using the formula
C = K - 273. - If the input is in Celsius, it strips the 'C' character and converts the remaining number to Kelvin using the formula
K = C + 273.
- If the input is in Kelvin, it strips the 'K' character and converts the remaining number to Celsius using the formula
-
Output:
- The script then outputs the result without spaces, in the required format.
Make sure you test the script with various inputs to ensure it works correctly.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.