iTranslated by AI
The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📑
Create a File at the Specified Path and Open in Editor: A Simple Command
Usage
$ edit
Usage: edit <file-path>
Example
$ edit foo/bar/index.html
Created dirs: foo/bar
Created file: foo/bar/index.html
$ edit foo/bar/index.html # If both the file and directory already exist, nothing is displayed, and the file is simply opened in the editor.
Features
- Automatically creates intermediate directories if they do not exist.
- Only logs when a directory is created (no output if it already exists).
- Automatically creates the file if it does not exist.
- Only logs when the file is created (no output if it already exists).
- Then opens the file in VSCode.
That's all. Just that.
In tutorials, when writing code to a file, you have to mkdir -p, touch, and then open the file—it's very tedious. I should have made this sooner. Now it's easy.
Code
Add the following to your .zshrc / .bashrc:
zshrc
# ...
# Create a file and open it with VSCode. Create intermediate directories if they don't exist.
edit() {
local filepath="$1"
if [ -z "$filepath" ]; then
echo "Usage: edit <file-path>"
return 1
fi
local dir
dir="$(dirname "$filepath")"
# Create the directory if it doesn't exist and log it
if [ ! -d "$dir" ]; then
mkdir -p "$dir"
echo " Created dirs: $dir"
fi
# Create the file (if it doesn't exist)
if [ ! -e "$filepath" ]; then
touch "$filepath"
echo " Created file: $filepath"
fi
# Open with VSCode
code "$filepath"
}
# ...
-
The reason it says
Created dirs:instead ofCreated directory:is to keep the character count consistent withCreated file:for better readability. ↩︎
Discussion