Cygwin - cd in bash script
Solution 1:
What kind of line endings does your script have? For Cygwin bash script to work properly (without having to set special options), it must have Unix line endings (LF) rather than DOS line endings (CR-LF). If you saved the script with DOS line endings, bash will see your argument to cd
as /c/Code/Project^M
, where ^M
is a CR, and won't find a directory by that name.
To see which kind of line endings it has, you can execute file scriptname
, where scriptname is the name of your script. To convert the script so that it has Unix line endings, execute d2u scriptname
.
Don't use Notepad to edit Cygwin bash scripts. It always saves files with DOS line endings.
Solution 2:
Unless you override, a script executes in its own copy of the shell (usually Bash). Then when the script exits, that instance of bash also exits. So your script CDs into a new directory and then exits, returning you to the original Bash--which never did a CD.
Two ways to work around it. You can use an alias instead of a script, e.g. in your .profile have
alias mycd="cd /c/Code/Project"
Another way is to tell Bash not to spawn a subshell by using the "dot" syntax
. myscript