echo bytes to a file

  • I'm trying to connect my rasberry Pi to some display using the i2c bus. To get started I wanted to manually write stuff, bytes in particular to a file. How do you write specific bytes to a file? I already read that one and I figured my problem should be solved by something like this

    echo -n -e \x66\x6f\x6f > byteFileForNow

    However, when I open up that file with nano, instead of foo I see:


    So the backslashes were escaped, but not the bytes themselves. I also tried the same only without the -e this time, so I would've exepected to see \x66\x6f\x6f, but got the same as before.

    So echo is escaping backslashes, backslashes alone and backslashes regardless of if it is supposed to.
    Any idea how to fix this?
    According to the man-page that should've done what I'm looking for.

  • rush

    rush Correct answer

    7 years ago

    You have to take your codes into quotes:

    echo -n -e '\x66\x6f\x6f' > byteFileForNow

    cause otherwise shell replaces \x to x before it goes to echo -e.

    ps. double escape will also work:

    echo -n -e \\x66\\x6f\\x6f > byteFileForNow

    I got it to work with quotes, double quotes though. I kinda new it was something obvious. Thanks!

    Just be carefull as echo is (usually) a builtin shell command. `bash` handle `\xHH` properly, but not all shells do.

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM