Search code examples
bashpathshcross-platformgit-bash

Convert Unix-Style Path to Windows


I have the same Bash script that I am running on Linux, Mac, and Windows (with Git Bash).

How can I make sure that the path is converted to a Windows-style path ONLY if running in Git Bash?

java -classpath "./path-1/subdir:./path-2" com.example.Main

Solution

  • You can test for the presence of cygpath.exe:

    classpath="./path-1/subdir:./path-2"
    
    if which cygpath.exe > /dev/null; then
      classpath="$(cygpath.exe -C ANSI -w -p "${classpath}")"
    fi
    
    java -classpath "${classpath}" com.example.Main
    

    But check first if you even need that conversion: in a bash shell script (even with Git For Windows bash), a Unix-style path will work when calling scripts/executables. However, strings passed as arguments are passed as-is.