Script to Copy the Current Directory

Script to Copy the Current Directory

Have you ever had that annoying feeling to use the mouse to copy your current directory from the terminal? The usual practice is executing the pwd command, select the output from the terminal using the mouse, then use the keyboard or mouse to copy the text. While using both hands to use the terminal, it is inconvenient to switch to the mouse. Things go beyond the tolerable threshold if the path to copy is too long and splits into two lines in the terminal.

However, as Linux users, we can implement a creative solution for this problem. This article explains how to create a new command to copy the current terminal directory into the clipboard without using the mouse.

Step 1:
To copy a text from the terminal into the clipboard, there is a utility called xclip. Install this tool if you don't have it already.

On Debian based distributions, use the following command:

sudo apt install xclip

Run the following command on Arch based distributions:
sudo pacman install xclip

Run the followoing command on Fedora
sudo dnf install xclip

Step 2:
Try the following command. Here we get the output of pwd command and pass it to the xclip command.

pwd | xclip -selection clipboard

After running this command in the terminal, try pasting the value in a text editor. You may notice a new line at the end.

Step 3:
Modify the command as shown below and run it again. The awk command will trim the new line character at the end.

pwd | awk '{printf $0}' | xclip -selection clipboard

Again check the output of the command by pasting the clipboard in a text editor.

Step 4:
Let's make this a command. Create a new file named copythis under the ~/bin folder. If the folder does not exist, create the folder. If the folder wasn't there already, you may have to restart the computer after Step 6 to let the system detect your command.

mkdir -p ~/bin
nano ~/bin/copythis

Step 5:
Add the following script to that file and save the changes.

pwd | awk '{printf $0}' | xclip -selection clipboard
In nano, use Ctrl+O and Ctrl+X to save the changes and exit.

Step 6:
Run the following command to make the script executable.

chmod +x ~/bin/copythis

Step 7:
Run the copythis command from the terminal and paste the clipboard value wherever you need.


Please leave a comment below if you find this script useful. If you have any questions or issues with running this script, I can help you in the comments section.


No comments

Post a Comment



© all rights reserved