chan go
chan go

Reputation: 137

pass long file argument from batch script to bash script in windows with cygwin

I am following this post:

http://blog.dotsmart.net/2011/01/27/executing-cygwin-bash-scripts-on-windows/

I need to execute a batch file with an argument and pass this argument to a bash script. The argument is a long file name with spaces, something like FILE WITH SPACES.xlsx.

In Windows:

c> program.cmd "FILE WITH SPACES.xlsx" # Windows adds the quotes to complete the name of the file.

The batch script must pass the name of the file "FILE WITH SPACES.xlsx" to a .sh script, something like this:

# program.sh "FILE WITH SPACES.xlsx"

Here is the problem, the file is passed without the quotes:

# program.sh FILE WITH SPACES.xlsx

The script program.sh has:

#!/bin/sh
anyprogram "$1"

The quotes are not passed and the program anyprogram doesn't locate the file FILE WITH SPACES.xlsx.

i tried escaping the " with \ but not work:

#!/bin/sh
anyprogram "\"$1"\"

Also, with:

#!/bin/sh
anyprogram '"$1"'

None looks to work, any suggestion?

Upvotes: 1

Views: 1654

Answers (1)

rubynorails
rubynorails

Reputation: 627

Batch files can be tricky with the way they handle double-quotes, and adding Bash variables can make things even trickier. Here is a solution that I believe solves your specific issue:

Batch file location: C:\Users\Jamey\Desktop\blah.bat

Batch file contents:

@ECHO OFF
ECHO I AM A BATCH FILE.
CD C:\Users\Jamey\Desktop
ECHO TESTING > %1
TYPE %1
ECHO.
SET scriptpath=/cygdrive/c/users/jamey/desktop
C:\cygwin64\bin\bash.exe -c "$scriptpath/program.sh "%1""

Bash script location: C:\Users\Jamey\Desktop\program.sh

Bash script contents:

#!/bin/bash

echo "I AM A BASH SCRIPT."
echo "A WINDOWS BATCH FILE TOLD ME TO SAY THIS: $1"
echo
ls -l "$1"
echo
cat "$1"
echo
rm -v "$1"

Here is the cmd.exe output from running blah.bat "FILE NAME WITH SPACES.txt":

C:\Users\Jamey\Desktop>blah.bat "FILE NAME WITH SPACES.txt"
I AM A BATCH FILE.
TESTING

I AM A BASH SCRIPT.
A WINDOWS BATCH FILE TOLD ME TO SAY THIS: FILE NAME WITH SPACES.txt

-rwxrwx---+ 1 Jamey None 10 Sep 24 09:05 FILE NAME WITH SPACES.txt

TESTING

removed 'FILE NAME WITH SPACES.txt'

Alternately, if you replaced 'rm -v' with 'cygstart', "FILE NAME WITH SPACES.txt" would open in Notepad. Same goes for Excel with .xlsx extensions. I hope this answers your question!

Upvotes: 2

Related Questions