Append text to file with shell script

Discussion in 'Mac Programming' started by wesg, Oct 12, 2008.

  1. macrumors regular

    wesg

    Joined:
    Jan 2, 2008
    Location:
    Toronto, ON
    #1
    I have a script that gathers data and will add it to a text file, without overwriting the current text.

    I can't quite get it to work properly.

    I've tried printing directly, but all this does is overwrite the existing text.

    Code:
    echo $output >> disk_space.txt
    where $output is my text and disk_space.txt is my text file.

    I've also tried using VI to edit the file, but I can't get that working either.

    Code:
    vi $file <<EOF
    :$
    $
    o
    $output
    ESC
    :w
    :x
    
    EOF
     
  2. Administrator

    Doctor Q

    Staff Member

    Joined:
    Sep 19, 2002
    Location:
    Los Angeles
    #2
    Your script should indeed append to disk_space.txt, not overwrite it, and I've never see it fail to work as specified. Perhaps there's another problem. For example, perhaps disk_space.txt already exists and does not have write permission so you can't modify it. Or perhaps you are running this command while the script is cd'ed to another location, so it's writing to /somewhere_else/disk_space.txt. You might change it to an absolute path.

    What kind of value is in $output? If it might contain punctuation characters, you'd be safer to put double quotes around it. In fact, I'd recommend doing that in any case.

    With my suggestions:
    Code:
    echo "$output" >> /Users/myname/Desktop/disk_space.txt
    If you want to post the full script (you can fake the data collecting part) some other cause for the problem might become apparent.

    Since programs like vi respond to one keypress at a time, rather than read a line at a time like most Unix shell commands, I don't think you can script a vi interaction the way you are trying to.
     

Share This Page