Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use $RANDOM in a makefile

I am making a makefile to rename files with a random number in it (I am a newbie in shell script). I don't understand why, but when I run the file $rand is given the value 'ANDOM'. When I run this outside of the makefile it works.

I run this in the Mac os terminal, in case it's helpful.

all: renamefiles

renamefiles:
    rand=$RANDOM && mv myfile.css $rand-myfile.css && mv myotherfile.css $rand-myotherfile.css
like image 504
romainberger Avatar asked Jan 18 '13 22:01

romainberger


2 Answers

  1. Wouldn't it be easier/better to use a date/time stamp so that the renamed files are listed in date order?

  2. You need to use two $ signs in the makefile for each $ that you want the shell to see.

Thus:

all: renamefiles

renamefiles:
    rand=$$RANDOM && \
    mv myfile.css      $$rand-myfile.css && \
    mv myotherfile.css $$rand-myotherfile.css

Or, with date/time stamps:

all: renamefiles

renamefiles:
    time=$$(date +'%Y%m%d-%H%M%S') && \
    mv myfile.css      $$time-myfile.css && \
    mv myotherfile.css $$time-myotherfile.css
like image 92
Jonathan Leffler Avatar answered Nov 15 '22 10:11

Jonathan Leffler


To use a random number within one or multiple make variables, the following works fine for me:

FOO="some string with \"$$rand\" in it"
BAR=" you may use it $$rand times."
foobar:
    rand=$$$$ && \
    echo $(FOO) $(BAR)
like image 45
Richard Kiefer Avatar answered Nov 15 '22 09:11

Richard Kiefer