开发者

Shell script pipeline: different behavior with or without xclip

开发者 https://www.devze.com 2023-04-03 23:47 出处:网络
I have a script named password-for-object which I normally run like that: $ password-for-object example.com

I have a script named password-for-object which I normally run like that:

$ password-for-object example.com
sOtzC0UY1K3EDYp8a6ltfA

I.e. it does an intricate hash calculation and outputs a password that I should use when accessing an object (for example, website) named example.com. I'll just double click the whole password, it gets copied into my buffer and I'll paste it into the form.

I've also learnt a trick on how to use such a script without making my password visible:

$ password-for-object example.com | xclip

This way output of a script ends up in X's primary buffer and I can insert it right into password field in the form and it's not shown on the screen.

The only problem with this way is that password-for-object outputs a string with trailing newline and thus "xclip" always catches up an extra symbol - this newline. If I omit output of newline in password-for-object, then I'll end up with messed up string without xclip, i.e. when I'm just putting it on the stdout. I use 2 shells: zsh and bash, and I'll get the following in zsh (note the extra % sign):

$ password-for-object example.com
sOtzC0UY1K3EDYp8a6ltfA%
$

Or the following in bash (note that prompt would be started on the same line):

$ password-for-object example.com
sOtzC0UY1K3EDYp8a6ltfA$

Any ideas on how to work around this issue? Is it p开发者_如何学运维ossible to modify the script in a way so it will detect that xclip is in the pipeline and only output newline if it isn't?


If you change password-for-object so that it doesn't output a newline, you can call it with a script like:

#!/bin/bash
password-for-object "$1"
if [ -t 1 ]
then
    echo
fi

The -t condition is described in the bash manual as:

-t fd

True if file descriptor fd is open and refers to a terminal.

See the following question:

  • How to detect if my shell script is running through a pipe?


Give this a try:

$ password-for-object example.com | tr -d '\n' | xclip

tr -d '\n' deletes the newline

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号