I want to write a script that obtains a list of all open programs and files, and then generates a shell script to re-open these files. For example, if I were editing the file example.txt using gedit, and editing the file myscript.js using geany, I would want to generate a script that could re-open both of these files using their respective programs. Is there any way to obtain a list of running programs and files from the command line?
Generally, it is not possible to do in the way you're approaching this, because the files opened in a text editor are not "open" in the sense programmers use the term (i.e. "having an active file handle somewhere within the program which can be used for I/O operations"). What most programs do is open the file, read the data in a memory buffer, then close the file. Saving a file is the same - open, write, close. Between open and save operations the file is not "open", it's just the copy of the data in the program's buffer in memory.
So it is generally not possible to figure out which files are currently loaded into the program's memory - however, the program itself does know that, so from inside the program it is trivial to implement an option to remember the list of open files on shutdown and re-open those files on startup. Many text editors, for example Kate and Sublime Text 2 do provide such option.
Some desktop environments, such as KDE (and also the old Gnome, I'm not sure about Gnome 3/Unity) also provide an option to save the list of running programs on shutdown and re-launch those programs on startup. Which combined with using a good editor kinda achieves what you're trying to do.
The command
ps aux
will display a list of running processes. In some cases, it will also list the files that are being edited with those programs, if the file name was used as a command line argument when starting the process. For example, I opened the filestuff.txt
using gedit, andgedit /home/anderson/Desktop/stuff.txt
was displayed in the output ofps aux
.There is trick you can try [may be in gnome]
this show files opened by a process [may not currently using]
History file
may help you.
For a DEMO just copy paste
diff <(cat ~/.local/share/recently-used.xbel) <(gedit /tmp/2.txt; cat ~/.local/share/recently-used.xbel)
from the output you can extract filename and process.
You can get a list of files opened with
gedit
today (July 1, 2020 in this case):Then call
gedit
and pass the filenames to it: