3

I'm trying to create an alias that will create a file and open it in VS Code.

Create an alias called create <filename> that will execute touch <filename> && code <filename>.

For example create app.js should execute touch app.js && code app.js.

Milad
  • 41
  • 1
  • 6

1 Answers1

2

From man bash, under ALIASES:

There is no mechanism for using arguments in the replacement text. If arguments are needed, a shell function should be used (see FUNCTIONS below)."

Thus:

create() { touch "$1"; code "$1"; }
Amadan
  • 191,408
  • 23
  • 240
  • 301
  • 1
    You should almost always double-quote variables (and parameters). Also, the function keyword is nonstandard; I'd recommend the syntax `create() { touch "$1"; code "$1"; }` – Gordon Davisson Aug 22 '18 at 02:56
  • @GordonDavisson: I agree about quoting. I disagree about `function`: the tag is [tag:bash], not [tag:sh], and so the standard is whatever `man bash` says. – Amadan Aug 22 '18 at 04:19
  • `man bash` says the `function` keyword is optional. Putting it there anyway simply makes your code less portable. – tripleee Aug 22 '18 at 05:58
  • @tripleee: I guess I should also replace all `x++` in C with `x += 1` because Ruby can't understand `++`, just in case... Fine... – Amadan Aug 22 '18 at 06:16
  • That's *reductio ad absurdum.* Shell scripts can be portable or specific to a particular shell. If you *need* features from a particular shell then of course striving for portability doesn't make any sense; but gratuitously wrecking otherwise portable code is just lazy. – tripleee Aug 22 '18 at 06:22
  • @tripleee: If it was a script designed for distribution, I'd agree with you. But we're talking about a user wanting to customise his specifically bash environment. OP will stuff this into their `.bashrc` and never look at it again. The chance of OP ever running it on Bourne shell is less than the chance of me converting C code into Ruby. I haven't even _seen_ Bourne shell in the last twenty years. Why are you so hung up on portability? – Amadan Aug 22 '18 at 06:29
  • Because it's not just the OP who ends up reading this. The broader argumentation is in my answer to https://stackoverflow.com/questions/11710552/useless-use-of-cat – tripleee Aug 22 '18 at 06:31