Jellicle
Jellicle

Reputation: 30206

Understanding tty + bash

I see that I can use one bash session to print text in another as follows

echo './myscript' > /dev/pts/0 # assuming session 2 is using this tty
# or
echo './myscript' > /proc/1500/fd/0 # assuming session 2's pid is 1500

But why does the text ./myscript only print and not execute? Is there anything that I can do to execute my script this way?

(I know that this will attract a lot of criticism which will perhaps fill any answers that follow with "DON'T DO THAT!" but the real reason I wish to do this is to automatically supply a password to sshfs. I'm working with a local WDMyCloud system, and it deletes my .authorized_keys file every night when I turn off the power.)

Upvotes: 3

Views: 2309

Answers (3)

Jellicle
Jellicle

Reputation: 30206

You can accomplish what you want by using an ioctl system call:

The ioctl() system call manipulates the underlying device parameters of special files. In particular, many operating characteristics of character special files (e.g., terminals) may be controlled with ioctl() requests.

For the 'request' argument of this system call, you'll want TIOCSTI, which is defined as 0x5412 in my header files. (grep -r TIOCSTI /usr/include to verify for your environment.)

I accomplish this as follows in ruby:

fd = IO.sysopen("/proc/#{$$}/fd/0", 'wb')
io = IO.new(fd, 'wb')
"puts 9 * 16\n".chars.each { |c| io.ioctl 0x5412, c };

Upvotes: 0

cEz
cEz

Reputation: 5062

Here is an example using a FIFO:

#!/usr/bin/bash

FIFO="$(mktemp)"
rm -fv "$FIFO"

mkfifo "$FIFO"

( echo testing123 > "$FIFO" ) &

cat "$FIFO" | sshfs -o password_stdin testing@localhost:/tmp $HOME/tmp

How you store the password and send it to the FIFO is up to you

Upvotes: 2

that other guy
that other guy

Reputation: 123450

why does the text ./myscript only print and not execute?

Input and output are two different things.

Writing to a terminal puts data on the screen. Reading from a terminal reads input from the keyboard. In no way does writing to the terminal simulate keyboard input.

There's no inherent coupling between input and output, and the fact that keys you press show up on screen at all is a conscious design decision: the shell simply reads a key, and then both appends it to its internal command buffer, and writes a copy to the screen.

This is purely for your benefit so you can see what you're typing, and not because the shell in any way cares what's on the screen. Since it doesn't, writing more stuff to screen has no effect on what the shell executes.

Is there anything that I can do to execute my script this way?

Not by writing to a terminal, no.

Upvotes: 4

Related Questions