1

I'm having trouble making a string out of repeated single characters. This works when I'm not assigning it to a variable:

printf "*%.0s" $(seq 1 $(expr $1 / 2))

This just assigns the script name to test:

printf -v test "*%.0s" $(seq 1 $(expr $1 / 2))

I also tried:

test=$(printf "*%.0s" $(seq 1 $(expr $1 / 2)))

But it does the same thing.

Why doesn't this work, and is there another way to build a string and assign it to a variable?

baiumbg
  • 23
  • 3
  • What's your expected output? – anubhava Nov 26 '15 at 11:14
  • I'm expecting `test` to contain $1 / 2 asterisks. (i.e. "****" if $1 / 2 results in 4) – baiumbg Nov 26 '15 at 11:18
  • You question has an answer [here](http://stackoverflow.com/questions/5799303/print-a-character-repeatedly-in-bash) . – sjsam Nov 26 '15 at 12:40
  • I tried that as well, but my variable still just contained my script name. I tried `test=$(echo "${testprep// /*}")` – baiumbg Nov 26 '15 at 12:49
  • What's the problem with `printf -v test "*%.0s" $(seq 1 $(expr $1 / 2))` code? It works fine for me. – anubhava Nov 26 '15 at 12:50
  • When I do `echo $test` it spits out test.sh (which is my script name) – baiumbg Nov 26 '15 at 12:54
  • That's a pretty cool method. I usually do `printf "%*s" $(($1/2)) " " | tr " " "*"` -- create a string of spaces of the required length, then translate the spaces to your desired character. – glenn jackman Nov 26 '15 at 14:07

1 Answers1

1

The value of test is fine; you just need to quote its expansion:

echo "$test"

Otherwise, the asterisks in the value are expanded to the contents of the current directory via pathname expansion.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • What if we have more than one asterisk? Shouldn't all of them be expanded ? – sjsam Nov 26 '15 at 13:20
  • As a single pattern, each additional asterisk is redundant. How it is explicitly interpreted is a matter of implementation, but conceptually each asterisk matches some substring of the final result. For example, `***` could match `foo` with each asterisk matching a single letter, or the first asterisk matching `foo` and the others matching empty strings, etc. – chepner Nov 26 '15 at 13:23
  • Good to know. Thank You – sjsam Nov 26 '15 at 13:24
  • `val=$(expr $1 / 2);s=$(printf "%-${val}s" "$2");test=$(echo "${s// /$2}"); echo "${test}";` I prepared this general solution for OPs problem. But not sure it it will work for all the inputs though. Works like `./somescript 30 *` or `./somescript 30 \\ ` – sjsam Nov 26 '15 at 13:37
  • Thanks! I knew it would come down to something very simple. The general solution might come in handy as well. – baiumbg Nov 26 '15 at 13:41
  • @baiumbg : Please test it thoroughly though and remember to escape the escape sequences ;) – sjsam Nov 26 '15 at 13:42
  • Also, don't use `expr`; `val=$(( $1 / 2 ))` – chepner Nov 26 '15 at 13:47