Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

How to echo a list on seperate lines in unix

  • 03-08-2011 04:24PM
    #1
    Registered Users, Registered Users 2 Posts: 5,761 ✭✭✭


    Hi - i have a variable (lets just call it $list) and want to output it line by line to a file. Does echo provide such a facility directly or do we need a for loop


Comments

  • Registered Users, Registered Users 2 Posts: 255 ✭✭boblong


    I'm sure there is some awesome way using just echo and I hope someone else posts their insight.

    Presuming $list is an array, here's what I would do:
    #!/bin/bash
    
    arr=(hello world something etc)
    echo ${arr[@]} | tr ' ' '\n' > file.txt
    

    This is probably quite the hack, but there it is :)


  • Registered Users, Registered Users 2 Posts: 3,141 ✭✭✭ocallagh


    edit: misread OP


  • Registered Users, Registered Users 2 Posts: 1,311 ✭✭✭Procasinator


    boblong wrote: »
    I'm sure there is some awesome way using just echo and I hope someone else posts their insight.

    Presuming $list is an array, here's what I would do:
    #!/bin/bash
    
    arr=(hello world something etc)
    echo ${arr[@]} | tr ' ' '\n' > file.txt
    

    This is probably quite the hack, but there it is :)

    Won't work for strings with spaces in them, like:
    arr=('hello world' 'something' 'etc')
    

    As hello world would be split.

    One solution would be to replace all the spaces in the strings with a character you know won't be in the input (in this example, _), and tr them back to spaces.
    echo ${arr[@]// /_} | tr '_ ' ' \n'
    

    However OP, I believe your best best is to use a for loop on ${list[@]}.


  • Registered Users, Registered Users 2 Posts: 368 ✭✭backboiler


    Hi - i have a variable (lets just call it $list) and want to output it line by line to a file. Does echo provide such a facility directly or do we need a for loop

    Does the input arrive line-by-line?
    Have you seen the difference between
    echo $line
    
    and
    echo "$line"
    
    (i.e. with double quotes). The latter may do what you want if the input is formatted that way since it stops the shell interpreting whitespace sequences (it converts them to a single space).


Advertisement