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
- Writing to the Clipboard: To send data from a Bash script to the clipboard, use the
xclipcommand. For example, to send the contents of a file to the clipboard, execute the following command:
bashcat 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.
- Reading from the Clipboard: To retrieve clipboard content within a script, use the following command:
bashxclip -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
- Writing to the Clipboard:
xselcan also write data to the clipboard. The following command functions similarly toxclip:
bashecho "Hello, world" | xsel --clipboard --input
Here, --clipboard specifies the clipboard, and --input writes the data.
- Reading from the Clipboard: To read clipboard content, use:
bashxsel --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.