Quantcast
Channel: Appending a current date from a variable to a filename - Unix & Linux Stack Exchange
Viewing all articles
Browse latest Browse all 6

Answer by Gilles for Appending a current date from a variable to a filename

$
0
0

You seem to have mixed up several things.

set today = 'date +%Y' looks like tcsh syntax, but even in tcsh it assigns the string date +%Y to the variable today, it doesn't run the date command. As you're probably using bash or some other POSIX shell, the syntax of an assignment is today=some_value (with no spaces around the equal sign). To run the command and assign its output to the variable, use command substitution:

today=$(date +%Y-%m-%d)

(I've also completed the date specification). You can use backquotes instead of dollar-parentheses, but it's prone to being visually confused with forward quotes, and the rules for when you need quotes inside a backquoted command are pretty complex and implementation-dependent, so it's better not to stick to $(…) (which has the same effect with a saner syntax).

You used & at the end of several commands. That makes the command execute in the background, which is not wanted here. I suspect you meant &&, which means to execute the next command only if the first command succeeded.

today=$(date +%Y-%m-%d)
mkdir -p The_Logs &&
find …

An alternative to using && after each command is to start your script with set -e. This tells the shell to stop executing the script as soon as any command returns a nonzero status (except for commands in if conditions and a few other cases).

set -e
today=$(date +%Y-%m-%d)
mkdir -p The_Logs
find …

Your find command is fine but probably doesn't do what you intend to do (though I don't know for sure what that is).

You're creating a directory with mkdir and then immediately traversing it with find. That won't be useful unless the directory already exists. Did you mean to create a directory for today's logs and move recent files from The_Logs to a directory called e.g. The_Logs.2012-02-11?

mkdir -p "The_Logs.$today"
find The_Logs -mtime -1 -exec mv {} "The_Logs.$today" \;

Or did you mean to rename today's log files to add the suffix $today? That requires calculating the different file name for each file to move.

find The_Logs -mtime -1 -exec sh -c 'mv "$0" "$0.$today"' {} \;

Note that I used -mtime, to move files based on their modification time, and not -atime, which is the time the file was last read (if your system keeps track of that — if it doesn't, the atime may be as far back as the mtime).


Viewing all articles
Browse latest Browse all 6

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>