Reputation: 73
I have a situation where I need to invoke a UNIX Shell from a windows CMD file. This is invoked as below:
sh -c path/script.sh
The challenge I am having is path is passed as a parameter to the windows cmd and contains the backward slash () to delimit the path. So a command execution like so:
sh -c e:\scriptpath\test.sh fails as sh correctly reports: e:scriptpathtest.sh does not exist.
Escaping the \ with a \ works: e.g. sh -c e:\\scriptpath\\test.sh will work.
The question is: how do I include the \ in the entered path parameter from within the windows cmd file? e.g. if path is entered as e:\scriptpath, it will automatically get converted to e:\\scriptpath?
Upvotes: 1
Views: 5528
Reputation: 30218
Never change the %path%
environment variable in the way described (set /p path=Enter path
). Use another name instead (e.g. set /p _path=Enter path
). The %path%
variable has a special meaning in Windows environment and its proper value has vital importance here. See also PATH
command.
Any user input should be thoroughly checked before using, e.g.
%variable:StrToFind=NewStr%
etc.: Variable Edit/ReplaceSave below code snippet with .bat
or .cmd
file extension, e.g. 32134824.cmd
:
@ECHO OFF
SETLOCAL EnableExtensions
:UserInput
rem empty the `_path` variable
set "_path="
rem or set a default value for it as follows:
set "_path=e:\scriptpath\test.sh"
rem prompt for user input
set /p "_path=Enter path [default=%_path%]:"
rem treat the case `set "_path="` and the user pressed only ˙Enter˙
if not defined _path echo wrong path & goto :UserInput
rem or set a default value instead: if not defined _path set "_path=%CD%\test.sh"
rem check if the file exists:
if not exist "%_path%" echo %_path%: file does not exist & goto :UserInput
rem translate to Unix filename conventions
set "_path=%_path:\=/%"
rem or set "_path=%_path:\=\\%"
rem next `sh` command is merely echoed for debugging purposes
echo sh -c %_path%
Further resources (required reading):
Upvotes: 0
Reputation: 20032
Windows also supports a forward slash between directories.
Try sh -c e:/scriptpath/test.sh
Upvotes: 0