-1

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

Haru Suzuki
  • 142
  • 10
  • Please [edit] your question to include a [mcve] with concise, testable sample input and expected output. It's OK to provide a link to some previous question for reference but we shouldn't NEED to visit that reference for your question to make sense stand-alone. As written we don't know what output you expect, nor what output you got that you didn't expect, nor what you mean by "not working". – Ed Morton Feb 19 '22 at 18:30

2 Answers2

1

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))}
pmf
  • 24,478
  • 2
  • 22
  • 31
0

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612