In this tutorial, you will learn how to show the public IP, location and the timezone of your server/computer in a bash script, and then save the output into a text file.
There are a lot of sites where you can just visit them and they will show your public IP.However, sometimes you need this data returned on a terminal or other project, so to make this possible, a bash script would be the perfect choice to use.
The service that we are using for this tutorial is ipinfo.io. You can also use any other service you like, including your own site.
The bash script below will return a json response as shown below, this response means this data is available that we can retrieve from ipinfo.io. For example, if you want to retrieve country location then we need to call ipinfo.io/country
#!/bin/bash
curl ipinfo.io
Output
{
"ip": "xxxx",
"city": "x",
"region": "x",
"country": "x",
"loc": "xxx",
"org": "xxx",
"postal": "xxxx",
"timezone": "xxxxx",
"readme": "x"
Show Public IP
To show your server's Public IP call ip on the bash script
#!/bin/bash
curl ipinfo.io/ip

Show Country
If you want to retrieve your server's country data, then you need to call country
on the curl call
#!/bin/bash
curl ipinfo.io/country

Show Region
To display region simply call ipinfo.io/region
#!/bin/bash
curl ipinfo.io/region

Show City
To show city make a curl call to ipinfo.io/city
#!/bin/bash
curl ipinfo.io/city

Show timezone
To show the timezone of the server from where you are executing the bash script, use
#!/bin/bash
curl ipinfo.io/timezone

Save the output into a file
If you want to save the output data depending the call that you are making on the bash script, then you can use the example below
#!/bin/bash
country="$(curl ipinfo.io/country)"
echo $country >> country.txt

This script will not display the country on the terminal but it will write it to the country.txt
file instead. If you want to get the script to display the country in the terminal and in the country.txt
file at the same time, then you can use >> to append the data to a file and cat command to read the content of country.txt
#!/bin/bash
country="$(curl ipinfo.io/country --silent)"
echo "Country: "$country >> country.txt
cat country.txt

Conclusion
In this tutorial, you learned how to make a bash script to get public data about your system.