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! Below is a bash script that takes a temperature value in Celsius (ending with 'C') or Kelvin (ending with 'K') and returns the inverse value accordingly.
#!/bin/bash if [ -z "$1" ]; then echo "Usage: $0 <temperature>" exit 1 fi input=$1 temp=${input::-1} scale=${input: -1} if ! [[ "$temp" =~ ^-?[0-9]+$ ]]; then echo "Invalid temperature value." exit 1 fi case "$scale" in K|k) celsius=$(( temp - 273 )) echo "${input} -> ${celsius}C" ;; C|c) kelvin=$(( temp + 273 )) echo "${input} -> ${kelvin}K" ;; *) echo "Unknown temperature scale. Please use 'C' for Celsius or 'K' for Kelvin." exit 1 ;; esacTo use this script, save it as
temp.sh, make it executable withchmod +x temp.sh, and then you can run it with a temperature value as an argument.Examples:
./temp.sh 122KThis will output:
122K -> -151C./temp.sh -151CThis will output:
-151C -> 122KMake sure the script handles both positive and negative numbers and properly checks for valid input formats.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.