4

I want to create a markdown file and open it simultaneously

$ touch ~/Documents/Ubuntu/drafts.md; open ~/Document/Ubuntu/drafts.md

The solution is cumbersome, is there a shortcut to handle such a task?

2 Answers 2

3

There's no such shortcut, Apparently, one could use Alt+. according to Sebastian Stark's answer

touch ${filename}
xdg-open <alt>+<.>

If your shell uses libreadline ( which /bin/dash on Ubuntu does not, but bash does ), then you can use that shortcut.


You can also create a file with shorter number of characters via bash:

: > ${filename}; xdg-open ${filename}

In this case, : command is built-in no-op command, which only returns exit status of 0 for success, but the trick here is that shell creates new or truncates existing file designated by ${filename}. xdg-open opens the said filename in default editor, since it will be just a plain file.

If you want to go even shorter, you can use bash history expansion feature to reuse command parameters:

: > myfile.txt ; xdg-open !#:1

If portability is a concern, you should use $_ for other shells. Of course, you can turn these into function or alias and call the alias or function name; call it something like mko() for "make and open":

# function definition to put in ~/.bashrc
mko(){  : > "$1"; xdg-open !#:1 }
# call it as so:
mko ~/Documents/myfile.md

Making a function also has advantage in adding a template to the file, if you need that:

mko(){ 
cat > "$1" <<EOF
### HEADING1
- bullet 1
- bullet 2
EOF 

xdg-open "$1" 
}

Sidenote: in case you also need to create directories along the path, you should use mkdir -p, see the related question.

Sidenote No.2: dessert's answer actually addresses a very fair point: most text editors do allow specifying a pathname for new file as one of their arguments. However, in cases where file has to exist - otherwise you get No such file or directory error - well, you can use this answer. Consider also that > truncates an existing file, so this can be useful where you want to quickly clear the file and start adding new content.

3

Let the editor create the file

Most (if not all) editors automatically create the file if you open them with a filename of a nonexistent one. You can save the touch and simply open the new file directly, e.g.:

nano ~/Document/Ubuntu/drafts.md
vim ~/Document/Ubuntu/drafts.md
leafpad ~/Document/Ubuntu/drafts.md

This will create the new empty file and open it. Like your approach it will fail if a directory needs to be created in the process.

1
  • That's what I'd do, might want to do something like nano $(mktemp -f XXXXXX.txt) to make a random file (or use date to ensure no collisions). Set the one-liner as an alias in your ~/.bashrc file, AND/OR set a hotkey to the alias/oneliner in your desktop manager.
    – pbhj
    Jan 12, 2019 at 15:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .