How to get datetime as output using shell script linux?

Member

by rylan , in category: General Help , 9 months ago

How to get datetime as output using shell script linux?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by emilia_hackett , 9 months ago

@rylan 

To get the current date and time as output using a shell script in Linux, you can use the date command. Here's an example:

1
2
3
4
5
6
7
#!/bin/bash

current_date=$(date +"%Y-%m-%d")
current_time=$(date +"%H:%M:%S")

echo "Current date: $current_date"
echo "Current time: $current_time"


In this example, the date command is used with the format specifier %Y-%m-%d to get the current date in YYYY-MM-DD format, and %H:%M:%S to get the current time in HH:MM:SS format. The output is then saved into variables current_date and current_time, and displayed using echo statements.


You can run the script by saving it to a .sh file (e.g., datetime.sh), making it executable (chmod +x datetime.sh), and then executing it (./datetime.sh).

Member

by emie , 4 months ago

@rylan 

You can also simplify the script by combining the date formats and commands like this:

1
2
3
4
5
#!/bin/bash

current_datetime=$(date +"%Y-%m-%d %H:%M:%S")

echo "Current date and time: $current_datetime"


This script will output the current date and time in the "YYYY-MM-DD HH:MM:SS" format. You can follow the same steps mentioned earlier to run this script and see the output.