乐闻世界logo
搜索文章和话题

How do you get the current date and time in a shell script?

1个答案

1

Obtaining the current date and time in Shell scripts can be achieved through various methods. One very common and straightforward approach is to use the date command. Here are several practical ways to utilize this command:

Basic Usage

bash
# Get the current date and time current_date_time="$(date)" echo "Current date and time: $current_date_time"

Specifying Format

If you require a specific date format, you can leverage the + option of the date command to customize the output. For instance, to output the date in YYYY-MM-DD format and the time in HH:MM:SS format:

bash
# Specify date format current_date="$(date +'%Y-%m-%d')" current_time="$(date +'%H:%M:%S')" echo "Current date: $current_date" echo "Current time: $current_time"

Practical Example

Suppose you are developing a backup script that needs to include date and time in the backup filename to differentiate between versions. You can implement the date command as follows:

bash
# Get the current date and time in the format YYYYMMDD-HHMMSS current_datetime="$(date +'%Y%m%d-%H%M%S')" # Create backup backup_file="backup-$current_datetime.tar.gz" tar -czf "$backup_file" /path/to/directory echo "Backup file created: $backup_file"

These examples illustrate effective techniques for incorporating date and time in Shell scripts to address diverse real-world requirements.

2024年8月14日 17:31 回复

你的答案