your programing

Bash 스크립트에서 클립 보드로 /로부터 파이프

lovepro 2020. 9. 28. 09:50
반응형

Bash 스크립트에서 클립 보드로 /로부터 파이프


Bash에서 클립 보드로 /로부터 파이프 할 수 있습니까?

장치 핸들과의 배관이든 보조 애플리케이션을 사용하든 아무것도 찾을 수 없습니다.

예를 들어, /dev/clip장치가 클립 보드에 연결되어 있다면 다음과 같이 할 수 있습니다.

cat /dev/clip        # Dump the contents of the clipboard
cat foo > /dev/clip  # Dump the contents of "foo" into the clipboard

다룰 수있는 클립 보드가 많이 있습니다. X Windows 기본 클립 보드에 내용을 저장하려는 Linux 사용자 일 것입니다. 일반적으로 대화하려는 클립 보드에는 대화 할 수있는 유틸리티가 있습니다.

X의 경우 xclip(및 기타)가 있습니다. xclip -selection c작동 클립 보드에 데이터를 보낼 것입니다 Ctrl + C, Ctrl + V대부분의 응용 프로그램에.

Mac OS X를 사용하는 경우 pbcopy.

Linux 터미널 모드 (X 없음)에 있는 경우 클립 보드가있는 gpm또는 화면 을 살펴보십시오 . screen명령을 시도하십시오 readreg.

Windows 10 이상 또는 cygwin에서는 /dev/clipboard또는 clip.


별칭을 사용하고 있는지 확인하십시오. xclip="xclip -selection c"그렇지 않으면 Ctrl+ v사용하여 다른 위치에 다시 붙여 넣을 수 없습니다 .

echo test | xclip    

Ctrl+v === test


설치

# You can install xclip using `apt-get`
apt-get install xclip

# or `pacman`
pacman -S xclip

# or `dnf`
dnf install xclip

액세스 권한이없는 경우 apt-get도를 pacman,도 dnf, 소스는 사용할 수 있습니다 소스 포지 .

설정

세게 때리다

에서 다음 ~/.bash_aliases을 추가합니다.

alias setclip="xclip -selection c"
alias getclip="xclip -selection c -o"

. ~/.bash_aliases프로필을 사용 하거나 다시 시작 하여 새 구성을로드하는 것을 잊지 마십시오 .

물고기

에서 다음 ~/.config/fish/config.fish을 추가합니다.

abbr setclip "xclip -selection c"
abbr getclip "xclip -selection c -o"

변경 사항을 적용하려면 터미널을 다시 시작하여 피시 인스턴스를 다시 시작하는 것을 잊지 마십시오.

용법

이제 사용 setclip하고 getclip, 예를 :

$ echo foo | setclip
$ getclip
foo

macOS에서는 내장 pbcopypbpaste명령을 사용 합니다.

예를 들어 다음을 실행하면

cat ~/.bashrc | pbcopy

+ 단축키를 ~/.bashrc사용 하여 파일 내용 을 붙여 넣을 수 있습니다 .Cmdv


시험

xclip

xclip - command line interface to X selections (clipboard) 

남자


Debian / Ubuntu / Mint의 xsel

# append to clipboard:
cat 'the file with content' | xsel -ib

# or type in the happy face :) and ...
echo 'the happy face :) and content' | xsel -ib

# show clipboard
xsel -b

# Get more info:
man xsel

설치

sudo apt-get install xsel

와,이 질문에 대한 답변이 얼마나 많은지 믿을 수 없습니다. 나는 그들 모두를 시도했다고 말할 수는 없지만 상위 3 또는 4를 시도했지만 그들 중 누구도 나를 위해 일하지 않습니다. 나를 위해 일한 것은 doug라는 사용자가 작성한 댓글 중 하나에있는 답변이었습니다. 나는 그것이 매우 도움이된다는 것을 알았 기 때문에 대답으로 다시 말하기로 결정했습니다.

xcopy 유틸리티를 설치하고 터미널에있을 때 다음을 입력합니다.

Thing_you_want_to_copy|xclip -selection c

myvariable=$(xclip -selection clipboard -o)

나는 pbpaste 및 pbcopy를 권장하는 많은 답변을 발견했습니다. 이러한 유틸리티를 사용하고 있지만 어떤 이유로 저장소에서 사용할 수없는 경우 항상 xcopy 명령에 대한 별칭을 만들고 pbpaste 및 pbcopy라고 부를 수 있습니다.

alias pbcopy="xclip -selection c" 
alias pbpaste="xclip -selection clipboard -o" 

그러면 다음과 같이 보일 것입니다.

Thing_you_want_to_copy|pbcopy
myvariable=$(pbpaste)

다음은 여러 플랫폼에서 작동하는 클립 보드를 읽기 위해 bash 스크립트를 사용할 준비가되었습니다. 기능 (예 : 더 많은 플랫폼)을 추가하는 경우 여기에서 스크립트를 편집하십시오.

#!/bin/bash
# WF 2013-10-04
# multi platform clipboard read access
# supports
#   Mac OS X
#   git shell / Cygwin (Windows)
#   Linux (e.g. Ubuntu)

#
# display an error
#
error() {
  echo "error: $1" 1>&2
  exit 1
}

#
# getClipboard
#
function getClipboard() {
 os=`uname`
      case $os in 
        # git bash  (Windows)
        MINGW32_NT-6.1)
          cat /dev/clipboard;;
        # Mac OS X
        Darwin*)
          pbpaste;;  
        # Linux 
        Linux*)
          # works only for X clipboard - a check that X is running might be due
          xclip -o;;
        *)
          error "unsupported os $os";;
      esac
}

tmp=/tmp/clipboard$$
getClipboard >$tmp
cat $tmp
# comment out for debugging
rm $tmp

Linux 용 Windows 하위 시스템에서는 clip.exe를 사용하여 클립 보드에 복사 할 수 있습니다.

cat file | clip.exe

|pipe 명령 을 사용하십시오 . 그리고 >그것은 작동하지 않을 것이기 때문에 명령이 아닙니다.


2018 답변

클립 보드 -cli를 사용하십시오 . 실제 문제없이 macOS, Windows, Linux, OpenBSD, FreeBSD 및 Android에서 작동합니다.

다음과 함께 설치하십시오.

npm install -g clipboard-cli

그러면 할 수 있습니다

echo foo | clipboard

당신이 원하는 경우에, 당신이 할 수있는 별명에, cb당신에 다음을 넣어 .bashrc, .bash_profile또는 .zshrc:

alias cb=clipboard


Windows (Cygwin 포함)에서 cat /dev/clipboard또는 기사 echo "foo" > /dev/clipboard에서 언급 한대로 시도 하십시오.


Mac 전용 :

echo "Hello World" | pbcopy
pbpaste

이들은 /usr/bin/pbcopy/usr/bin/pbpaste.


Linux에는 다른 클립 보드가 있습니다. X 서버에는 하나가 있고 창 관리자에는 다른 하나가있을 수 있습니다. 표준 장치는 없습니다.

예, CLI에서 screen 프로그램은 Emacsvi같은 다른 응용 프로그램과 마찬가지로 자체 클립 보드를 가지고 있습니다 .

X에서는 xclip 을 사용할 수 있습니다 .

이 스레드에서 다른 가능한 답변을 확인할 수 있습니다. http://unix.derkeiler.com/Newsgroups/comp.unix.shell/2004-07/0919.html


Windows (Cygwin)에서 복사하여 클립 보드에 붙여 넣기 :

보다:

$ clip.exe-?

CLIP 설명 : 명령 줄 도구의 출력을 Windows 클립 보드로 리디렉션합니다. 이 텍스트 출력은 다른 프로그램에 붙여 넣을 수 있습니다. 매개 변수 목록 : /? 이 도움말 메시지를 표시합니다. 예 : DIR | CLIP 현재 디렉토리 목록의 사본을 Windows 클립 보드에 넣습니다. CLIP <README.TXT readme.txt의 텍스트 사본을 Windows 클립 보드에 넣습니다.

getclip (shift + ins 대신 사용할 수 있음!), putclip (echo oaeuoa | putclip.exe를 사용하여 클립에 넣음)도 있습니다.


  xsel -b

x11에 대한 작업을 수행하며 대부분 이미 설치되어 있습니다. xsel의 man 페이지를 살펴보면 그만한 가치가 있습니다.


이것은 필요한 작업을 수행하는 간단한 Python 스크립트입니다.

#!/usr/bin/python

import sys

# Clipboard storage
clipboard_file = '/tmp/clipboard.tmp'

if(sys.stdin.isatty()): # Should write clipboard contents out to stdout
    with open(clipboard_file, 'r') as c:
        sys.stdout.write(c.read())
elif(sys.stdout.isatty()): # Should save stdin to clipboard
    with open(clipboard_file, 'w') as c:
        c.write(sys.stdin.read())

경로 어딘가에 실행 파일로 저장합니다 (파일에 저장했습니다 /usr/local/bin/clip. 클립 보드에 저장할 항목을 파이프 할 수 있습니다 ...

echo "Hello World" | clip

And you can pipe what's in your clipboard to some other program...

clip | cowsay
 _____________
< Hello World >
 -------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

Running it by itself will simply output what's in the clipboard.


A few Windows programs I wrote years ago. They allow you dump, push, append and print the clipboard. It works like this:

dumpclip | perl -pe "s/monkey/chimp/g;" | pushclip

It includes source code: cmd_clip.zip


There are a couple ways. Some of the ways that have been mentioned include (I think) tmux, screen, vim, emacs, and the shell. I don't know emacs or screen, so I'll go over the other three.

Tmux

While not an X selection, tmux has a copy mode accessible via prefix-[ (prefix is Ctrl+B by default). The buffer used for this mode is separate and exclusive to tmux, which opens up quite a few possibilities and makes it more versatile than the X selections in the right situations.

To exit this mode, hit q; to navigate, use your vim or emacs binding (default = vim), so hjkl for movement, v/V/C-v for character/line/block selection, etc. When you have your selection, hit Enter to copy and exit the mode.

To paste from this buffer, use prefix-].

Shell

Any installation of X11 seems to come with two programs by default: xclip and xsel (kinda like how it also comes with both startx and xinit). Most of the other answers mention xclip, and I really like xsel for its brevity, so I'm going to cover xsel.

From xsel(1x):

Input options

-a, --append

append standard input to the selection. Implies -i.

-f, --follow

append to selection as standard input grows. Implies -i.

-i, --input

read standard input into the selection.

Output options

-o, --output

write the selection to standard output.

Action options

-c, --clear

clear the selection. Overrides all input options.

-d, --delete

Request that the current selection be deleted. This not only clears the selection, but also requests to the program in which the selection resides that the selected contents be deleted. Overrides all input options.

Selection options

-p, --primary

operate on the PRIMARY selection (default).

-s, --secondary

operate on the SECONDARY selection.

-b, --clipboard

operate on the CLIPBOARD selection.

And that's about all you need to know. p (or nothing) for PRIMARY, s for SECONDARY, b for CLIPBOARD, o for output.

Example: say I want to copy the output of foo from a TTY and paste it to a webpage for a bug report. To do this, it would be ideal to copy to/from the TTY/X session. So the question becomes how do I access the clipboard from the TTY?

For this example, we'll assume the X session is on display :1.

$ foo -v
Error: not a real TTY
details:
blah blah @ 0x0000000040abeaf4
blah blah @ 0x0000000040abeaf8
blah blah @ 0x0000000040abeafc
blah blah @ 0x0000000040abeb00
...
$ foo -v | DISPLAY=:1 xsel -b # copies it into clipboard of display :1

Then I can Ctrl-V it into the form as per usual.

Now say that someone on the support site gives me a command to run to fix the problem. It's complicated and long.

$ DISPLAY=:1 xsel -bo
sudo foo --update --clear-cache --source-list="http://foo-software.com/repository/foo/debian/ubuntu/xenial/164914519191464/sources.txt"
$ $(DISPLAY=:1 xsel -bo)
Password for braden:
UPDATING %%%%%%%%%%%%%%%%%%%%%%% 100.00%
Clearing cache...
Fetching sources...
Reticulating splines...
Watering trees...
Climbing mountains...
Looking advanced...
Done.
$ foo
Thank you for your order. A pizza should arrive at your house in the next 20 minutes. Your total is $6.99

Pizza ordering seems like a productive use of the command line.

...moving on.

Vim

If compiled with +clipboard (This is important! Check your vim --version), Vim should have access to the X PRIMARY and CLIPBOARD selections. The two selections are accessible from the * and + registers, respectively, and may be written to and read from at your leisure the same as any other register. For example:

:%y+    ; copy/yank (y) everything (%) into the CLIPBOARD selection (+)
"+p     ; select (") the CLIPBOARD selection (+) and paste/put it
ggVG"+y ; Alternative version of the first example

If your copy of vim doesn't directly support access to X selections, though, it's not the end of the world. You can just use the xsel technique as described in the last section.

:r ! xsel -bo ; read  (r) from the stdout of (!) `xsel -bo`
:w ! xsel -b  ; write (w) to the stdin of    (!) `xsel -b`

Bind a couple key combos and you should be good.


From this thread, there is an option which does not require installing any gclip/xclip/xsel third-party software.

A perl script (since perl is usually always installed)

use Win32::Clipboard;
print Win32::Clipboard::GetText();

I have found a good reference: https://unix.stackexchange.com/questions/69111/

In my case I would like to paste content on the clipboard and also to see what is been pasted there, so I used also the tee command with a file descriptor:

echo "just a test" | tee >(xclip -i -selection clipboard)

>() is a form of process substitution. bash replaces each with the path to a file descriptor which is connected to the standard input of the program within the parentheses.

The teecommand forks your command allowing you to "pipe its content" and see the result on standard output "stdout"

you can also create aliases to get and write on the clipboard, allowing you to use "pbcopy" and "pbpaste" as if you where on MAC. In my case, as I use zsh I have this on my aliases file:

(( $+commands[xclip] )) && {
    alias pbpaste='xclip -i -selection clipboard -o'
    alias pbcopy='xclip -selection clipboard'
}

the (( $+command[name] )) in zsh tests if the command "name" is installed on your system, then both aliases are grouped with {}. the && is a binary AND, if a then b, hence if you have xclip then the aliases will be set.

echo "another test" | tee >(pbcopy)

To get your clipboard content just type:

pbpaste | "any-command-you-need-here"

If you're like me and run on a linux server without root privileges and there's no xclip or gpm you could workaround this issue by just using a temporary file. For example:

$ echo "hello world" > ~/clip
$ echo `cat ~/clip`
hello world

in macOS use pbpaste

eg:

update the clipboard

pbpaste | ruby -ne ' puts "\|" + $_.split( )[1..4].join("\|") ' | pbcopy

enjoy.


There is also xclip-copyfile.


Although >1 year later, I share a slightly different solution. Hope this is useful for somebody.

Yesterday I found myself with the question: "How to share the clipboard between different user sessions?". When switching between sessions with ctrlaltF7 - ctrlaltF8, in fact, you can't paste what you copied.

I came up with the following quick & dirty solution, based on a named pipe. It is surely quite bare and raw, but I found it functional:

user1@host:~$ mkfifo /tmp/sharedClip

then in the sending terminal

user1@host:~$ cat > /tmp/sharedClip

last, in the receiving terminal:

user2@host:~$ cat /tmp/sharedClip

Now, you type or paste anything in the first terminal, and (after hitting return), it will appear immediately in the receiving terminal, from where you can Copy/Paste again anywhere you like.

Of course this doesn't just strictly take the content from user1's clipboard to make it available in user2's clipboard, but rather it requires an additional pair of Paste & Copy clicks.

참고URL : https://stackoverflow.com/questions/749544/pipe-to-from-the-clipboard-in-bash-script

반응형