7

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
Zombo
  • 1
  • 62
  • 391
  • 407
romainberger
  • 4,563
  • 2
  • 35
  • 51

3 Answers3

11
  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
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • $RANDOM was the first I thought about but the time is definitely better. Thank you – romainberger Jan 21 '13 at 09:04
  • 2
    Be aware that `$RANDOM` is a builtin bash variable and not in all shells (unlike `$$`, should be available in all POSIX-compliant shells, see http://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: http://stackoverflow.com/a/6681727/470117 – mems Jun 20 '14 at 09:33
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)
Richard Kiefer
  • 1,814
  • 2
  • 23
  • 42
  • 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 :) – Richard Kiefer Feb 05 '15 at 13:57
0

You might need to surround a multi-letter macro name with braces (or parentheses), for example

${RANDOM}
$(RANDOM)

ref

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Zombo
  • 1
  • 62
  • 391
  • 407
  • 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}`. – Jonathan Leffler Jan 18 '13 at 23:35