Reputation: 135
I'm writing a small command line script for managing some data in my application.
I am utilizing STDIN
with fgets()
to read user input.
When I add a new bit of data, I can just use fgets()
to read the new data from STDIN
, then add it to the database.
Example CLI interface for adding data:
Value: <user input>
I can get this user input using:
$input = trim(fgets(STDIN));
Where I'm running into issues is the functionality of editing data that already exists.
What I would like to have is the previous value pre-filled into the user input.
Example CLI interface for editing data:
Value: <previous>
where <previous>
is the old value, and editable.
I have tried using fwrite()
to write to STDIN
, which it does, but the data written isn't editable and the cursor starts at the end of the data.
My Attempt:
// Prompt
echo 'Value: ';
// Try and put the old data into STDIN
fputs(STDIN, $old_data);
// Get the new value from STDIN
$new_data = trim(fgets(STDIN));
The interface ends up looking like this:
Value: <old_data>
^
Cursor Position
and <old_data>
isn't editable.
Then the returned data from the fgets(STDIN)
only gives me the data from after the cursor starting position.
I'm not sure if this is doable with PHP without any crazy libraries. Any help and ideas would be appreciated.
Upvotes: 2
Views: 293
Reputation: 6267
This will depends on your shell (I think), but you can do that with most xterm with a control character.
Documentation for BASH is here : https://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x361.html
Example:
echo "foo: bar\033[3D";
The character \033[<N>D
will move the cursor backward N columns, in this example 3, to place it at the beginning of bar.
I don't think this will do what you expect it to do. The old data will not be "editable" as you imagine. The user will not be able to move the cursor around, simply type over the old data. Also, pressing Enter will not submit what is "after" the cursor. So, you might want to look into ncurses
.
Alternatively, what is usually done in Linux world is a prompt like this:
Value (previous):
Meaning if you simply press "Enter", then "previous" is used. In your code if STDIN is empty then simply use previous.
Upvotes: 1