乐闻世界logo
搜索文章和话题

How to pipe to/from the clipboard in a Bash script

1个答案

1

In Bash scripts, interacting with the clipboard primarily involves two commonly used commands: xclip and xsel. These tools enable reading from or writing to the clipboard within Bash scripts. Below, I will explain the usage of each command and provide specific examples.

Using xclip

  1. Writing to the Clipboard: To send data from a Bash script to the clipboard, use the xclip command. For example, to send the contents of a file to the clipboard, execute the following command:
bash
cat file.txt | xclip -selection clipboard

Here, the cat file.txt command reads the file content and pipes it into xclip. The -selection clipboard parameter specifies that the data is sent to the system clipboard.

  1. Reading from the Clipboard: To retrieve clipboard content within a script, use the following command:
bash
xclip -selection clipboard -o

The -o option makes xclip output the clipboard content, which can then be processed further or saved to a file.

Using xsel

  1. Writing to the Clipboard: xsel can also write data to the clipboard. The following command functions similarly to xclip:
bash
echo "Hello, world" | xsel --clipboard --input

Here, --clipboard specifies the clipboard, and --input writes the data.

  1. Reading from the Clipboard: To read clipboard content, use:
bash
xsel --clipboard --output

The --output option outputs the clipboard content.

Example Script

Here is a simple Bash script that first writes text to the clipboard, then reads and prints the content:

bash
#!/bin/bash # Write text to clipboard echo "Sample text for clipboard" | xclip -selection clipboard # Wait for user input read -p "Press Enter to continue and fetch text from clipboard..." # Read clipboard content and print clipboard_content=$(xclip -selection clipboard -o) echo "Content from clipboard: $clipboard_content"

In this script, xclip is used, but xsel can replace the corresponding commands to achieve the same effect.

In summary, these tools simplify clipboard interaction in Bash scripts for both reading and writing data. This is particularly valuable in automation tasks, such as processing large text datasets and sharing content with other applications.

2024年8月14日 18:04 回复

你的答案