`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?
2 Answers
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.
-
But then I have to insert these lines into each script... Isn't there a way to configure VS code to always cd to the right folder automatically? Commented Feb 28, 2019 at 19:13
I found the answer here. To help others struggling with the same issue, here is a complete solution.
Make sure you have the "Code Runner" extension installed.
Go to File -> Preferences -> Settings (or click Ctrl+,).
Search for the setting "fileDirectoryAsCwd".
Click the checkbox.
Done!