Home > database >  Parse the output of a script and process the last line only before printing
Parse the output of a script and process the last line only before printing

Time:05-17

I have a simple CLI tool asking for a master password, and printing a string $USER $PASSWORD only if the master password is correct.

How to reproduce?

Here is a script just for demonstrating my use-case, the real script is in fact a CLI tool on which I have no control:

#!/usr/bin/env sh

printf "Enter master password: "
read -s password

echo

[ "$password" == "MasterPassword" ] && echo "user1 Passw0rd!"

Example of usage:

$ ./my-cli-tool
Enter master password: ********
user1 Passw0rd!

Issue

I don't want the password (Passw0rd!) to be printed on screen. I want to print only the user (user1), and just copy the password (Passw0rd!) to the clipboard (let's say with xclip -sel clipboard).

What I have tried?

If the first line (Enter master password) were not there, I would have done:

./my-cli-tool |
    while read -r USER PASSWORD
    do
        echo $USER
        echo -n $PASSWORD | xclip -sel clipboard
    done

But my issue is that I should type the master password when the prompt asks for, and so the first line is always printed. I have tried to run ./my-cli-tool | tail -1: the prompt is not shown, although if I type the master password, it only prints user1 Passw0rd!, so I can do the command above to copy the password into the clipboard.

Question

Do you have any idea to:

  • always show the prompt on screen for the master password
  • only print the user
  • copy the password to the clipboard

Expected output

Basically, I would like that kind of output:

$ ./my-cli-tool | solution
Enter master password: ********
user1

And have Passw0rd! copied into my clipboard.

CodePudding user response:

I've simply modified your answer a little bit -

./my-cli-tool | {
    x=$(dd bs=1 count=1 2>/dev/null)
    while [ "$x" != : ]; do
        printf %c "$x";
        x=$(dd bs=1 count=1 2>/dev/null)
    done
    printf %s ": "
    while read -r USER PASSWORD
    do
        echo $USER
        echo -n $PASSWORD | xclip -sel clipboard
    done
}

Lemme know if it works.

EDIT: Updated logic. Uses dd.

  • Related