Search code examples
bashmingw-w64

Bash parsing Windows path to a variable in MINGW64


I want to be able to run 7z.exe in a bash script, but for my script triggers No such file or directory at the 7z path definition:

#declare 7zip path
7zip="/c/Program\ Files/7-Zip"

#call it
$7zip/7z x ./$filename -o$extract_folder

I tried from this post:

7zip_exe="$(find /c/Program\ Files/7-Zip -name 7z.exe | head -n 1)"

Which also results in No such file or Directory.

When I investigate in Git bash (MINGW64), I can go to 7-Zip folder easily:

<user> MINGW64 /d/workdir
$ cd /c/Program\ Files/7-Zip/

<user> MINGW64 /c/Program Files/7-Zip
$ ls
7-zip.chm     7z.dll*  7zCon.sfx*  History.txt  descript.ion
7-zip.dll*    7z.exe*  7zFM.exe*   Lang/        readme.txt
7-zip32.dll*  7z.sfx*  7zG.exe*    License.txt

But when I want to parse it to a variable, the space is interpreted as a path cut:

<user> MINGW64 /d/workdir
$ t="/c/Program\ Files/7-Zip"

<user> MINGW64 /d/workdir
$ ls $t
ls: cannot access '/c/Program\': No such file or directory
ls: cannot access 'Files/7-Zip': No such file or directory

But this works:

<user> MINGW64 /d/workdir/NX2506
$ t="$(/c/Program\ Files/7-Zip)"
bash: /c/Program Files/7-Zip: Is a directory

And ls /c/Program\ Files/7-Zip displays 7z.exe.

What am I missing?


Solution

  • Define the variable by using either double-quotes or by escaping the space. Not both.

    So either

    t="/c/Program Files/7-Zip"
    

    or

    t=/c/Program\ Files/7-Zip
    

    And then use double-quotes around the variable:

    ls "$t"
    

    Also, variable names must start with a letter. See the definition of name in the Bash Reference Manual :

    name

    A word consisting solely of letters, numbers, and underscores, and beginning with a letter or underscore. Names are used as shell variable and function names.