Trying to write a small script edit in .bashrc : Close a terminal after opening a program

79 Views Asked by At

I recently changed my OS to Linux Mint, and have switched over to using the i3 window manager. To open files from terminal, I use xdg-open. This results in a file (.pdf, .txt, etc.) to be opened by a default selected application (if you want, you can open .txt files with Firefox). You can also just type "open whatever.ext" into the command line and it will work. The thing is, I would like to configure my .bashrc file so that the terminal window closes after running this command, or else I'm stuck with two windows for the price of one.

I know using dmenu (or rofi in my case) also opens applications, but I'm spending most of my time in terminal. It would just be really clean to go "open math_hw.pdf" and have the terminal be replaced by the PDF viewer, rather than me going [rofi -> pdf veiwer -> open new file -> select file] with the GUI.

Since I have never written any scripts before in my life, and googling for the past few hours has been in vain, I would appreciate any suggestions on how I should write the script.

I've tried xopen() { xdg-open "$@" && exit; } and writing a function

function op() {
  xdg-open $1 > /dev/null 2>&1 & disown
}

both allow me to save the bash file with `source ~/.bashrc' in the terminal without giving any errors, but still don't change anything

2

There are 2 best solutions below

1
amphetamachine On BEST ANSWER

The following function, when added to your .bashrc, will launch xdg-open in the background and immediately exit the shell (which usually closes the terminal window).

op() {
    xdg-open "$@" &
    exit
}

Example usage case: You open a terminal and type op my-file.pdf at which point the terminal exits and whatever PDF viewer/editor you have configured opens. Unfortunately (maybe?), if it cannot figure out how to open the file, the terminal will still close.

Important Note: When you make changes to your .bashrc or .bash_profile, in order for the changes to take effect, you must either:

  • Close your terminal window and start another one -OR-
  • Run . ~/.bashrc in the terminal -OR-
  • Run exec $SHELL in the terminal

Any one of these three actions will apply the changes.

5
tjm3772 On

If you want to literally replace the terminal with the new process, there's exec for that. Add something like this to your bashrc:

xopen() {
  exec xdg-open "$@"
}

And then a simple xopen math_hw.pdf will replace the terminal process with the PDF viewer process.