I have some code:

char *tty_name = ttyname(STDIN_FILENO);
char command[255] = "/usr/sbin/writevt -t "; strcpy(stpcpy(command + 21, tty_name), " -T ' \r'"); system(command);

It writes a "space" and a "carriage return" to the current TTY. Which works fine for my uses. But, i'm wondering if there is a simpler way of achieving this? I've tried this:

echo -e " \r > $(tty)"

But, it isn't working.


You could simply do (assuming the echo accepts the -n as "do not print a trailing new line") :

echo -ne " \r" > "$(tty)"

Redirections (>) do not work inside quotes.

A "one line" example:

$ echo -n Test; echo -ne " \r " > $(tty); echo "New string"
New string

A more robust (portable) solution is to use printf:

$ printf Test;     printf ' \r' > "$(tty)"    ; echo "New string"

And (as required by POSIX) use the common /dev/tty as the name of the process tty:

printf ' \r' > /dev/tty

Related: Does Posix require any devices?

  • Awesome. It's working. Thank you. I'm closing this thread. – ignatius Jun 15 '18 at 21:56

You could instead open(2) /dev/tty and write to that:

#include <err.h>
#include <fcntl.h>
#include <stdio.h>

int main(void)
    int ttyfd;
    if ((ttyfd = open("/dev/tty", O_WRONLY)) == -1)
        err(1, "open /dev/tty failed");
    dprintf(ttyfd, " \rxxx");
    return 0;

(" \r" by itself may not be visible as it could be clobbered by the next written line.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.