Home > database >  executing variable substitution/String manipultion N times
executing variable substitution/String manipultion N times

Time:02-19

Repeating same command n times. Question has been asked before

But methods in that question are not working for variable assignments

Eg.

var='abc,xyz,mnx,duid'
for f in `seq 3`; do var=${var%,*}; done

Above works but using it in function as described in other question does't work

Eg.

repeat() { num="$"; shift; for f in $(seq $num); do $1; done; }
repeat 3 'var=${var%,*}'
repeat 3 "var=${var%,*}"

Doesn't work

CodePudding user response:

Variable expansions and assignments aren't processed after expanding variables. You need to use eval to re-execute it as a shell command.

You also have a typo, "$" should be "$1".

repeat() { num="$1"; shift; for f in $(seq $num); do eval "$1"; done; }
repeat 3 'var=${var%,*}'
echo "$var" # output = abc

Note that the argument needs to be in single quotes, otherwise the variable expansion will be processed once before calling the function.

CodePudding user response:

Based on your sample data

var='abc,xyz,mnx,duid'

you can also have the same effect by concatenating the search terms multiple times

var=${var%,*,*,*}

That said, you could also do things like

var=${var%$(printf ',*%.0s' {1..3})}

or

n=3; var=${var%$(printf ',*%.0s' $(seq $n))}
  •  Tags:  
  • bash
  • Related