Use $RANDOM in a makefile

10,477

Solution 1

  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

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)
Share:
10,477
romainberger
Author by

romainberger

Updated on July 06, 2022

Comments

  • romainberger
    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
    Jonathan Leffler over 11 years
    This 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 or rand=$${RANDOM}.
  • romainberger
    romainberger over 11 years
    $RANDOM was the first I thought about but the time is definitely better. Thank you
  • mems
    mems almost 10 years
    Be 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
    Richard Kiefer over 9 years
    Thanks 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 :)