简体   繁体   中英

How to create a string with shell output (backticks) in Bash?

I have been trying to create a string with a variable number of characters in it for a benchmark program. I am trying to use this to set up my messages string:

messages=`perl -e 'print "X" x $size'`

The goal is to create a dynamic number of characters. For example, if $size is 1 then there will be one X. If size is 5 then messages will be XXXXX. This doesn't seem to work and the output is blank.

Am I misunderstanding something?

The reason that $size is not evaluated by bash is that you enclosed it in single quotation marks ( ' ). This gets more obvious if you use the $(...) syntax instead of the backticks:

messages=$( perl -e 'print "X" x $size' )

The principle is that everything inside single quotes is not touched by bash (only the quotes are stripped finally after word splitting), while things in double quotes get the various shell expansions (without quotes even more).

Thus Perl here gets $size and can only try to evaluate this as a perl variable.

As already said by other Diego, swapping the quotation signs around can help:

messages=$( perl -e "print 'X' x $size" )

Try with:

messages=`perl -e 'print "X" x shift' $size`

You need to evaluate $size in bash, not in perl. This way you pass it as a command-line argument to the script and in Perl you fetch with a single shift .

Another possible solution:

messages=`perl -e "print \"X\" x $size"`

or even, playing with quotes:

messages=`perl -e "print 'X' x $size"`

Well, IMHO calling perl and awk for simple string processing is hackish . A simple task like this can be done directly:

in='X' out='' x=5
for ((i = 0; i < x; ++i)); do out+="$in"; done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM