简体   繁体   中英

bash: string concatenation with newline

I try to append strings to a string in a bash script.

my code:

page_list=""
for ... do
  $page_list+=$"duration $mdelay \n"
done
echo $page_list >> $list_file

But it gives the following error

 +=duration 0.12 \n: command not found

Update : removing the leading $ before page_list resolves the problem, but no new line is added to the list_file .

Update 2 : None of the solutions offered works

By using $ in at the beginning of the string, Bash is trying to run it as a command, just remove it

page_list=""

page_list+="duration $mdelay \n"

You can use the $'\n' bashism, or you can simply do:

page_list="duration $mdelay
"

or

nl='
'
page_list="duration ${mdelay}${nl}"

I wish I could comment to ask for more clarification on what $list_file is. The key here should be to echo within the loop and output the result to a text file. The result of each echo will be written onto a newline automatically.

#!/bin/bash

file_list="one two three" 
mdelay="0.12"

for i in $file_list
do
    i+=" duration $mdelay"
    echo $i >> output.txt
done

Result (in output.txt):

one duration 0.12
two duration 0.12
three duration 0.12

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