2

I have a question regarding a shortcut use of "code".

My Goal is to simultaneously:

  1. Open a new file in VS Code, and also:
  2. Automatically save that new file to my current working directory

Basically I want to execute "touch hello.c | code hello.c" in one command.

Is there an alias, function or shortcut I can include in .zshrc to help automate this combination of steps?

2 Answers 2

3

The correct answer isn't an alias, aliases don't have arguments. They are text substitutions.

Instead you want a small function, similar to this:

function makefile {
  touch "$1" && code "$1"
}

That takes a single argument, the name of the file. The "&&" ensures that if the creation of the file fails, code won't be executed.

1
  • Nice work quick draw, McGraw!
    – bmike
    Commented Nov 26, 2023 at 20:42
1

According to the documentation, you can simply issue the second part after the pipe:

code ./hello.c

VSCode will create the file since it doesn’t exist and then open the newly created file. The ./ guarantees making the file in the current directory but is optional so feel free to skip it.

But there’s a way to do what you need - a function - to do this:

newcode() {
    if [ -n "$1" ]
    then
        touch "$1"
        code "$1"
    else
        echo no file to create or open
    fi
}

You must log in to answer this question.

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