Linux time to variable

Custom format for time command

I’d like to use the time command in a bash script to calculate the elapsed time of the script and write that to a log file. I only need the real time, not the user and sys. Also need it in a decent format. e.g 00:00:00:00 (not like the standard output). I appreciate any advice. The expected format supposed to be 00:00:00.0000 (milliseconds) [hours]:[minutes]:[seconds].[milliseconds] I’ve already 3 scripts. I saw an example like this:

But I only need the real time, not the user and sys. Also need it in a decent format. e.g 00:00:00:00 (not like the standard output). In other words, I’d like to know how to turn the time output into something easier to process.

New bash versions (>= 4.2) do offer a printf syntaxe for this: printf -v TimeStamp «%(%s)T» -1 and printf «%(%a %d %b %Y %T)T\n» $TimeStamp values could be -1 : now, -2 : Start of bash session, Integer : Unix timestamp

6 Answers 6

You could use the date command to get the current time before and after performing the work to be timed and calculate the difference like this:

#!/bin/bash # Get time as a UNIX timestamp (seconds elapsed since Jan 1, 1970 0:00 UTC) T="$(date +%s)" # Do some work here sleep 2 T="$(($(date +%s)-T))" echo "Time in seconds: $" printf "Pretty format: %02d:%02d:%02d:%02d\n" "$((T/86400))" "$((T/3600%24))" "$((T/60%60))" "$((T%60))"" 

Notes: $((. )) can be used for basic arithmetic in bash – caution: do not put spaces before a minus as this might be interpreted as a command-line option.

EDIT:
Additionally, you may want to take a look at sed to search and extract substrings from the output generated by time.

Example for timing with milliseconds (actually nanoseconds but truncated to milliseconds here). Your version of date has to support the %N format and bash should support large numbers.

# UNIX timestamp concatenated with nanoseconds T="$(date +%s%N)" # Do some work here sleep 2 # Time interval in nanoseconds T="$(($(date +%s%N)-T))" # Seconds S="$((T/1000000000))" # Milliseconds M="$((T/1000000))" echo "Time in nanoseconds: $" printf "Pretty format: %02d:%02d:%02d:%02d.%03d\n" "$((S/86400))" "$((S/3600%24))" "$((S/60%60))" "$((S%60))" "$" 

DISCLAIMER:
My original version said

but this was edited out because it apparently did not work for some people whereas the new version reportedly did. I did not approve of this because I think that you have to use the remainder only but was outvoted.
Choose whatever fits you.

Читайте также:  Linux info about domain

Источник

Redirect output of time command in unix into a variable in bash?

I just want to capture the output of a time command i.e: X=$(time ls) or $(time ls) | grep real The time function spits it to the console though. How do I do this?

5 Answers 5

$ # captures output of command and time $ time=$( TIMEFORMAT="%R"; < time ls; >2>&1 ) # note the curly braces $ # captures the time only, passes stdout through $ exec 3>&1 4>&2 $ time=$(TIMEFORMAT="%R"; < time ls 1>&3 2>&4; > 2>&1) bar baz $ exec 3>&- 4>&- 

The time will look like «0.000» using TIMEFORMAT=»%R» which will be the «real» time.

could you explain a little how this works ? I’ve uses a snippet like this cargo cult style for years. Whats stream 3 and 4 ? and the ‘-‘ ?

@Sirex: Streams 3 and 4 are streams created by the exec command in my answer using available file descriptors. Any available file descriptors could be used. Streams 3 and 4 are copies of 1 ( stdout ) and 2 ( stderr ), respectively. This allows the output of ls to pass normally to stdout and stderr via 3 and 4 while the output of time (which normally goes to stderr ) is redirected to the original stdout (1) and then captured in the variable using command substitution. As you can see in my example, the filenames bar and baz are output to the terminal. .

Running this with tracing mode ( set -x ) adds some unwanted output to the result. I solved it by adding set +x so that scripts won’t fail while debugging. So the solution that worked for me: time=$(set +x; TIMEFORMAT=»%R»; < time ls 1>&3 2>&4; > 2>&1)

Time writes its output to STDERR rather than STDOUT. Making matters worse, by default ‘time’ is a shell builtin command, so if you attempt ‘time ls 2>&1’ the ‘2>&1’ only applies to ‘ls’.

The solution would probably be something like:

/usr/bin/time -f 'real %e' -o OUTPUT_FILE ls > /dev/null 2>&1 
REALTIME=$(cat OUTPUT_FILE | cut -f 2 -d ' ')

There are more fancy ways to do it, but that is the clear/simple way.

I am interested in doing this without -o. Can you post one of the fancy methods you were thinking of 🙂 ?

The cleanest approach is to combine a temp file and use GNU’s time.

command="sleep 1" saved_timing=`mktemp` /usr/bin/time --format="%E real" -o "$saved_timing" $command elapsed=$(cat "$saved_timing") echo $elapsed 

This will not bypass normal command output and you don’t have to care about the file either since it will be deleted on it own.

Читайте также:  Linux сменить основную группу пользователя

@Dennis Williamson’s answer is great, but it doesn’t help you store the command’s output in one variable, and the output of time in another variable. This is actually not possible using file descriptors.

If you want to record how long a program takes to run, you could do this by just subtracting the start time from the end time. Here is a simple example that shows how many milliseconds a program took to run:

START_TIME=$(date +%s%3N) OUTPUT=$(ls -l) ELAPSED_TIME=$(expr $(date +%s%3N) - $START_TIME) echo "Command finished in $ELAPSED_TIME milliseconds" 

This is not quite as accurate as the time command, but it should work perfectly fine for most bash scripts.

Unfortunately Mac’s date command doesn’t support the %N format, but you can install coreutils ( brew install coreutils ) and use gdate :

START_TIME=$(gdate +%s%3N) OUTPUT=$(ls -l) ELAPSED_TIME=$(expr $(gdate +%s%3N) - $START_TIME) echo "Command finished in $ELAPSED_TIME milliseconds" 

Источник

How to Create a Timestamp Variable in Bash Script?

A timestamp is a set of characters or encoded data that identifies the occurrence of a specific event, typically denoting the date and time. The timestamp format varies depending on the system or application generating it, but in Bash Script Linux, the most common format is YYYY-MM-DD HH:MM:SS.

They can be incredibly useful when debugging scripts or analyzing log files. This helps you track the progress of your scripts and pinpoint exactly when a particular event occurred, making it easier to troubleshoot any issues that may arise.

This article will discuss how a user can create a timestamp using the following examples.

  • How to Create a Timestamp Variable in Bash?
  • Using the date Command
  • Using the printf Command
  • Logging Script Start and End Times
  • Creating a Backup

How to Create a Timestamp Variable in Bash?

Depending on your requirements and preferences, there are several ways to create a timestamp variable in Bash. Here are some common methods:

Example 1: Using the date Command

The date command is a standard Unix command that prints the current date and time in various formats. To store the output of the date command in a variable, you can use command substitution, which is done by enclosing the command in $() or backticks (`):

#!/bin/bash timestamp=$(date +'%Y-%m-%d %H:%M:%S') echo "The current timestamp is $timestamp"

Code Explanation:

– The date command is used with the +%Y-%m-%d %H:%M:%S format string.

Читайте также:  Linux memory management kernel

– The output is stored in the timestamp variable, which can be used later in the script.

The output of the code can be seen by executing the bash script below:

Example 2: Using the printf Command

The printf command is versatile and can format and print various data types, including dates and times. To create a timestamp string with printf, you can use the date command to get the current time in seconds since the Unix epoch (January 1, 1970) and then format it as desired. Here’s an example:

#!/bin/bash epoch=$(date +%s) timestamp=$(printf "%(%Y-%m-%d %H:%M:%S)T" "$epoch") echo "The current timestamp is $timestamp"

Code Explanation:

– The date +%s command returns the current time in seconds stored in the epoch variable.

– The printf command then uses the %()T format specifier to convert the epoch time to a timestamp string in the specified format.

– The resulting string is stored in the timestamp variable.

The output of the code can be seen by executing the bash script below:

Example 3: Logging Script Start and End Times

To log the start and end times of a Bash script, you can create two timestamp variables at the beginning and end of the script and then use them in your log messages. Here’s an example:

#!/bin/bash start_time=$(date +'%Y-%m-%d %H:%M:%S') echo "Script started at $start_time" # Your script commands here echo "Hello, world!" end_time=$(date +'%Y-%m-%d %H:%M:%S') echo "Script ended at $end_time"

The output of the code can be seen by executing the bash script below:

Example 4: Creating a Backup

A user can generate the backup of any directory by incorporating the time stamp, and one of its examples in the form of a Bash script is mentioned below:

#!/bin/bash timestamp=$(date +'%Y-%m-%d_%H-%M-%S') mkdir "backup_$timestamp" cp -r /home/foss/Documents "backup_$timestamp/"

Code Explanation:

– The cp command copies the contents of the /home/foss/documents directory to the backup directory named backup_.

– The is a string representing the current date and time in the format YYYY-MM-DD_HH-MM-SS.

The execution of this bash script will create a new folder with the name of a “backup_$timestamp”.

Conclusion

The use of timestamps in Linux bash script comes with many benefits, such as a user can track log files for auditing and troubleshooting purposes. Another benefit is that users can manage files or schedule tasks and automate processes. This article has discussed in detail how a user can create a bash script with a timestamp by discussing multiple examples.

Источник

Оцените статью
Adblock
detector