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?

7
  • What's your expected output? Commented Nov 26, 2015 at 11:14
  • I'm expecting test to contain $1 / 2 asterisks. (i.e. "****" if $1 / 2 results in 4) Commented Nov 26, 2015 at 11:18
  • You question has an answer here . Commented Nov 26, 2015 at 12:40
  • I tried that as well, but my variable still just contained my script name. I tried test=$(echo "${testprep// /*}") Commented Nov 26, 2015 at 12:49
  • What's the problem with printf -v test "*%.0s" $(seq 1 $(expr $1 / 2)) code? It works fine for me. Commented Nov 26, 2015 at 12:50

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

What if we have more than one asterisk? Shouldn't all of them be expanded ?
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.
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 \\
Thanks! I knew it would come down to something very simple. The general solution might come in handy as well.
@baiumbg : Please test it thoroughly though and remember to escape the escape sequences ;)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.