curl -s "wttr.in?0" retrieves the weather data, and by adding grep -oP '(?<=[°])(\d+)' or a similar regex, you can isolate just the integer representing the degrees. This approach strips away the unit labels like Celsius or Fahrenheit, providing a clean number for scripting or display purposes.
Understanding the Base Command
The foundation of this operation is thecurl utility combined with the wget and cURL commands philosophy of handling web requests efficiently. By default, running curl wttr.in returns a full ASCII art weather forecast, which includes location names, date headers, and detailed hourly breakdowns. To get a more concise view suitable for parsing, you typically add the parameter ?0. This flag tells the service to return only the current condition summary rather than the multi-day forecast.
When you execute curl -s "wttr.in?0", the response looks something like this:
+---------------------+
| Mostly Cloudy |
| •••••••••••• |
| 18°C / 13°C |
| |
| Wind speed: 5 km/h |
+---------------------+
Your goal is to isolate the 18 from that line. The -s flag suppresses the progress meter, making the output cleaner for piping into other tools. Without it, curl might print download statistics to stderr, which can interfere with simple text processing if not redirected properly.
Parsing with Grep and Sed
Once you have the raw text, you need a method to extract the specific number. The most robust way is usinggrep with Perl-compatible regular expressions (PCRE). You want to find digits that are immediately preceded by the degree symbol (°).
You can use the following command structure:
curl -s "wttr.in?0" | grep -oP '(?<=[°])\d+'
Here is how each part functions:
- curl -s "wttr.in?0": Fetches the simplified weather data silently.
- |: Pipes the standard output to the next command.
- grep -oP: Uses the
-oflag to print only the matched part of the line, and-Penables Perl regex syntax. - (?<=[°])\d+: This is the regex pattern.
(?<=[°])is a lookbehind assertion that ensures the match is preceded by the degree symbol but does not include it in the output.\d+matches one or more digits.
-P (common in older BSD-based systems like macOS), you can use sed instead. The command would look like this:
curl -s "wttr.in?0" | sed -n 's/.*\(.\([0-9]*\)C.*/\1/p'
This sed command searches for a line containing digits followed by 'C' (for Celsius) or 'F'. It captures the digits inside parentheses and prints only that capture group. Note that this assumes the output format remains consistent with standard wttr.in responses. If the weather service changes its ASCII layout, this regex may need adjustment.
Handling Unit Conversion
By default, wttr.in returns temperatures in Celsius. If you require Fahrenheit, you can append?u to the URL: curl -s "wttr.in?0u". The parsing logic remains largely the same, but you must ensure your regex accounts for the 'F' suffix if you are using the sed approach. For example, changing C to [CF] in the pattern allows flexibility.
It is important to note that the lookbehind approach with grep -P is generally safer because it ignores the unit letter entirely. Whether the output says 18°C or 64°F, the pattern (?<=[°])\d+ will correctly extract 18 or 64 respectively. This makes your script more resilient to regional settings or user preferences configured on the wttr.in side.
Integrating into Bash Scripts
Once you have the working one-liner, you can store the result in a variable for further use in automation tasks. This is particularly useful for monitoring scripts or dashboard widgets.TEMP=$(curl -s "wttr.in?0" | grep -oP '(?<=[°])\d+')
echo "Current temperature is $TEMP degrees"
Ensure that curl and grep are installed on your system. On minimal Linux distributions, grep might be a busybox implementation that lacks -P support. In such cases, falling back to awk or sed is necessary. For instance, an awk solution could be:
curl -s "wttr.in?0" | awk -F'[°]' '{print $2}' | awk '{print $1}'
This splits the string by the degree symbol and then takes the first word of the second field, effectively stripping any trailing characters. While slightly more verbose, it works across all POSIX-compliant environments. Always test these commands in your specific environment before deploying them to production servers, as network latency or API rate limits on wttr.in can occasionally cause empty outputs.
Frequently Asked Questions
Why does my command return an empty string?
This usually happens if the network request fails or if the wttr.in service is temporarily unavailable. Ensure you have internet access and check if the curl command returns HTTP 200. Additionally, verify that your locale settings do not alter the degree symbol, which could break the regex match.
Can I get the temperature in Kelvin?
The wttr.in service does not natively support Kelvin output via URL parameters. You must retrieve the Celsius or Fahrenheit value and convert it manually within your script using arithmetic expansion in bash or a calculation in Python or another language.
How do I handle errors if curl fails?
You should always check the exit status of curl. Use if ! curl -s ... ; then echo "Error"; fi to catch failures. This prevents your script from proceeding with empty variables, which could lead to unexpected behavior in downstream processes or notifications.
Is there a JSON alternative to parsing ASCII art?
Yes, wttr.in supports JSON output if you set the header Accept: application/json. Using curl -H "Accept: application/json" wttr.in returns structured data that can be parsed with tools like jq, which is often more reliable than regex against ASCII art.
Does this work on Windows PowerShell?
Standard PowerShell does not have native grep or sed commands. You would need to use PowerShell cmdlets like Select-String or -match operators to achieve similar results. Alternatively, installing WSL (Windows Subsystem for Linux) allows you to run the original bash commands directly.