Search code examples
linuxcommand-line-interfacesh

How to run command in WHILE-DO bash command


I'm trying to run echo in a loop in which the wait time varies. The following command does already do this

/bin/sh -c 'trap exit TERM; while :; do echo test; sleep 10 ; done;'"

However, I don't it to be 10 seconds all the time, I want it to be a random number between 1 and 10. To generate a random number between 1 and 10 I constructed the following

$> min=1 && max=10
$> echo $(($RANDOM%($max-$min+1)+$min))

Now, my question is, how do I combine this. For example, I tried the following

$> /bin/sh -c 'trap exit TERM; while :; do echo test; sleep $(($RANDOM%($max-$min+1)+$min)) ; done;'"

But this gives errors

/bin/sh: -c: line 0: syntax error near unexpected token `('
/bin/sh: -c: line 0: `trap exit TERM; while :; do echo test; min=1 && max=10 && sleep $RANDOM%($max-$min+1)+$min ; done;

Any suggestions how to combine the two? Or if there is a better way, I'm also all ears!!


Solution

  • Apparently max and min are not exported and so they are undefined in the subshell.

    Try

    bash -c 'max=10; min=1; trap exit TERM; while :; do echo test; sleep $(($RANDOM%($max-$min+1)+$min)); done'
    

    Alternatively, export the variables you want to make visible to subprocesses.

    (If your sh implements RANDOM the way Bash does, then of course feel free to use sh instead; but this is not portable or recommended. See also Difference between Bash and sh)