Use $RANDOM in a makefile
10,477
Solution 1
Wouldn't it be easier/better to use a date/time stamp so that the renamed files are listed in date order?
You need to use two
$
signs in themakefile
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
Solution 2
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)
Author by
romainberger
Updated on July 06, 2022Comments
-
romainberger almost 2 years
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
-
Jonathan Leffler over 11 yearsThis evaluates the
make
variable RANDOM (which probably won't exist and isn't random). In this case, I think the trick is that you write$$
to get one$
to the shell:rand=$$RANDOM
orrand=$${RANDOM}
. -
romainberger over 11 years$RANDOM was the first I thought about but the time is definitely better. Thank you
-
mems almost 10 yearsBe aware that
$RANDOM
is a builtin bash variable and not in all shells (unlike$$
, should be available in all POSIX-compliant shells, see stackoverflow.com/a/8281456/470117). Make use the default shell. To specify which shell make will use, define a variable:SHELL = /bin/bash
or (via cmd line argument)make SHELL=/bin/bash
See: stackoverflow.com/a/6681727/470117 -
Richard Kiefer over 9 yearsThanks very much to @mems ' comment regarding the accepted answer. Although this answer does not tackle the stated use case, it fits the question I hope :)