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
Certainly! Here’s a bash script that converts temperatures between Celsius (C) and Kelvin (K). The script reads a temperature value with its unit (either 'K' for Kelvin or 'C' for Celsius) and outputs the inverse value (i.e., converts from Kelvin to Celsius or Celsius to Kelvin).
#!/bin/bash if [ $# -ne 1 ]; then echo "Usage: $0 [temperature][unit]" exit 1 fi input=$1 value=${input%[CK]} unit=${input: -1} if [[ ! $value =~ ^-?[0-9]+$ ]]; then echo "Invalid temperature value." exit 1 fi if [[ $unit == "K" ]]; then result=$((value - 273)) echo "${result}C" elif [[ $unit == "C" ]]; then result=$((value + 273)) echo "${result}K" else echo "Invalid unit. Use 'K' for Kelvin or 'C' for Celsius." exit 1 fiSave the above script to a file named
temp.shand make it executable using the following command:chmod +x temp.shNow, you can use the script to convert temperatures as specified:
./temp.sh 122K # outputs: -151C ./temp.sh -151C # outputs: 122KThe script takes a single argument as input, extracts the numeric part and the unit, performs the appropriate conversion, and prints the result in the specified format.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.