3

When I backup a file, I add a timestamp to it.

For example:

$ DATE=$(date +%F) $ cp file{,.$DATE.bk} $ ls file file.2012-06-20.bk 

There is a bash variable RANDOM, every time I echo it, it gives me different values:

$ echo $RANDOM 20511 $ echo $RANDOM 12577 $ echo $RANDOM 32433 

How can I define such kind of a variable DATE?

5 Answers 5

3

You could hold the command statement and evaluate it on use.

$ DATE="date +%F" $ echo $DATE date +%F $ echo `$DATE` 2012-06-20 
Sign up to request clarification or add additional context in comments.

Comments

3

You are attacking the problem from the wrong angle. Write a script which creates a backup.

#!/bin/sh for f; do cp "$f" "$f.$(date +%F).bk" done 

This is simple enough to go as a function in your .profile if you don't want to litter your $HOME/bin with basically a one-liner.

Comments

2

Bash has no such feature. You should use ksh93's discipline functions if you need getters/setters/properties, and generally anything that's going to require OO.

#!/usr/bin/env ksh function DATE.get { .sh.value=$(printf '%(%F)T') } cp file{,".${DATE}.bk"} 

I'm not aware of any other shell that can do this except perhaps through their respective loadable extension interfaces.

Comments

1

Bash has a variable that updates automatically that contains the number of seconds since the shell started.

You can set the value and it will update starting with that base. The disadvantage is that it uses an epoch seconds timestamp format. You can use date to convert it back.

Here's a demo:

$ bash $ echo "$SECONDS" 5 $ date +%s; SECONDS=$(date +%s); echo "$SECONDS" 1340191083 1340191083 $ sleep 10 $ date +%s; echo "$SECONDS" 1340191097 1340191097 $ date -d "@$SECONDS" Wed Jun 20 06:18:24 CDT 2012 $ date -d "@$SECONDS" +%F 2012-06-20 

The extra seconds are because of the startup time of Bash and the time it takes to type the commands.

$ bash -c 'echo $SECONDS' 0 

Comments

0

You need to edit the bash source code in order to provide it. But make sure you know what format everyone wants their date in before doing it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.