Skip to content

Instantly share code, notes, and snippets.

@DominoPivot
Created September 2, 2022 06:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DominoPivot/c5bb82019c690fa9d7f1a21187e2de83 to your computer and use it in GitHub Desktop.
Save DominoPivot/c5bb82019c690fa9d7f1a21187e2de83 to your computer and use it in GitHub Desktop.
Script that lets you be very lazy when it comes to creating/reopening a project in VS Code.
#!/bin/sh
if [ "$#" -ne 1 ]; then
cat <<- EOF
Usage: $0 PROJECT
Creates the ~/workspace/PROJECT directory if it doesn't exist and opens it in VS Code.
EOF
exit 1
fi
mkdir -p ~/workspace/"$1"
code ~/workspace/"$1"
@DominoPivot
Copy link
Author

DominoPivot commented Sep 2, 2022

Quick explanations for shell scripting newbies:

#!/bin/sh

The line above says the script should run using the /bin/sh command which should be a POSIX-compatible shell.

if [ "$#" -ne 1 ]; then

This checks if the number of arguments passed to the codep.sh script is not equal to 1. This is more of an internal detail, but [ and ] are actually not part of the syntax of the if statement, [ is a command, and "$#" -ne 1 ] are the arguments we passed to it.

cat <<- EOF
	Usage:	$0 PROJECT
	Creates the ~/workspace/PROJECT directory if it doesn't exist and opens it in VS Code.
EOF

The cat command is normally used to output the contents of a file, but here I'm using it to output a here-document, a special block of text that spans multiple lines. There are many ways to begin a here-document, <<- is one that strips leading TAB characters. EOF is an arbitrary word; whatever you type after the <<- and before the newline will be used as the delimiter to mark the end of the here-document. The closing delimiter has to be on its own line. I chose EOF which stands for End Of File.

mkdir -p ~/workspace/"$1"

The -p flag creates all missing directories in the provided path, and doesn't complain if some or all of them already exist.

code ~/workspace/"$1"

You might be wondering why all the variables I write are within quotations marks. This ensures the contents of the variable are not split on whitespace and parsed as path patterns. It's a good idea to pretty much always use variables within quotation marks, except inside a here-document.

@polypoyo
Copy link

exit 1 tells the shell that something went wrong. This is useful for scripting, but some shells can be configured to look different when the last command exited with a non-zero exit-code. Additionally, [ is actually a command that exits 0 when the condition inside passes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment