Running a script in the script folder

Posted on

Problem :

`In Visual Studio Code, when I write a bash script (with the first line “#!/bin/bash”) and click Alt+X, the script runs, however, its working folder is not the folder of the script itself, it’s the working folder of the project.
How can I tell VS Code to cd to the script folder before running it?

Solution :

It is not foolproof, but I generally use:

myname=${BASH_SOURCE[0]}
mydir=$(dirname "$myname")
cd "$mydir"

There are some issues with links and sourcing the file, therefore I say it is not fool-proof.

I found the answer here. To help others struggling with the same issue, here is a complete solution.

  1. Make sure you have the “Code Runner” extension installed.

  2. Go to File -> Preferences -> Settings (or click Ctrl+,).

  3. Search for the setting “fileDirectoryAsCwd”.

  4. Click the checkbox.

Done!

Leave a Reply

Your email address will not be published.