Powershell Docker Command Doesn't Work Like Bat File - docker

I'm trying to create a script that starts a docker container and mounts a local folder that contains spaces in the name. I can get it to work fine when I run a *.bat file with the docker run command:
docker run -p 8081:8081 -v "C:\Test Folder With Blanks":/zzz myimage jupyter lab --notebook-dir=/zzz--ip=0.0.0.0 --port=8081 --allow-root
But when I try to do the same in a Powershell script file, I get an error:
$CMD = 'docker run -p 8081:8081 -v "C:\Test Folder With Blanks":/zzz myimage jupyter lab --notebook-dir=/zzz--ip=0.0.0.0 --port=8081 --allow-root'
Invoke-Expression $CMD
docker: invalid reference format.
See 'docker run --help'.
I'm on Win10 and running Powershell in Visual Studio Code IDE.
Thanks for ideas.

First, the obligatory warning: Unless you have a command line stored as a single string somewhere and you either fully control or trust the content of the string, Invoke-Expression should generally be avoided.
You're seeing an inconsistency in how PowerShell treats compound tokens composed of directly concatenated quoted and unquoted parts.
Specifically, argument "C:\Test Folder With Blanks":/zzz is unexpectedly broken in two, i.e passed as two arguments.
The workaround is to quote the entire argument, i.e.
"C:\Test Folder With Blanks:/zzz"
Note: I'm assuming that docker doesn't actually require partial quoting in its arguments, which it shouldn't; however, there are high-profile CLIs on Windows that do, notably msiexec.
Alternatively, use an expression enclosed in (...) to compose your string; e.g.
("C:\Test Folder With Blanks" + ':/zzz')
There's no good reason to do so in this case, but it could be helpful if you need string interpolation in one part of your string ("..."), but not in another ('...').
General caveats:
Compared to cmd.exe and also POSIX-compatible shells such as bash, PowerShell has several additional metacharacters, notably # (at the start of a token), { / }, and ;. Therefore, you cannot always expect command lines written for these shells to work as-is in PowerShell.
As of PowerShell 7.2.2, passing arguments to external programs (such as docker) is fundamentally broken with respect to arguments that have embedded " characters and empty-string arguments - see this answer.
The general pattern of the inconsistency, as of PowerShell 7.2.2, is as follows:
If an argument:
starts with a quoted token - whether single- ('...') or double-quoted ("...") -
and has additional characters directly following the closing quote,
the first such character starts a separate argument.
E.g. "foo":bar / "foo"=bar / "foo"'bar' are passed as separate arguments foo and :bar / foo and =bar / foo and bar, respectively.
In other words:
You cannot compose a single string argument from a mix of quoted and unquoted / differently quoted tokens if the first token is quoted.
Conversely, it does work if the first token is unquoted, including an unquoted simple variable reference such as $HOME.
# OK: First token is unquoted.
PS> cmd /c echo foo"bar"'baz'last
foobarbazlast
# !! BROKEN: First token is quoted.
# !! Because each successive token is quoted too,
# !! each becomes its own argument.
PS> cmd /c echo 'foo'"bar"'baz'last
foo bar baz last
GitHub issue #6467 discusses this inconsistency; however, it has been closed, because the behavior is - surprisingly - considered by design.
This does not happen if the first token is unquoted; however, there are related bugs that start with unquoted tokens that similarly break arguments in two, related to their looking like named arguments to PowerShell (which is a PowerShell concept that doesn't apply when calling external programs):
GitHub issue #11646: an argument such as -foo=1,2 breaks parsing.
GitHub issue #6291: an argument such as -foo=bar.baz is broken in two at the (first) .

Related

Failed to process input: The parameter must begin with a / or -

I am running a Dockerfile but every time it stops at one point.
RUN powershell %windir%\system32\inetsrv\appcmd.exe set config /section:system.webServer/handlers /+"[name='Test',path='Test.cgi',verb='*',modules="IsapiModule",scriptProcessor="c:\Test.dll",resourceType="Unspecified", preCondition="bitness64"]"
Failed to process input: The parameter 'verb=*' must begin with a / or -
I am struggling for hours. What could be the reason?
You're trying to invoke appcmd.exe via PowerShell (powershell.exe), even though the appcmd.exe command line doesn't require the features of that shell - it seems to be composed of literal strings only.
Your use of %windir% implies that your Dockerfile uses the default shell on Windows, namely cmd.exe
Therefore, you should be able to formulate your appcmd.exe command line as you would submit it from a cmd.exe session:
RUN %windir%\system32\inetsrv\appcmd.exe set config /section:system.webServer/handlers /+[name='Test',path='Test.cgi',verb='*',modules='IsapiModule',scriptProcessor='c:\Test.dll',resourceType='Unspecified',preCondition='bitness64']
Note:
All quoting in the remainder of the argument that starts with /+ now uses only '...', for consistency; since no argument-internal " chars. are therefore in play, the need to escape them goes away.
No spaces are allowed in the remainder of the argument.
As for what you tried:
When you use the -Command / -c PowerShell CLI parameter (which is implied in the absence of -File), " characters to be passed through as part of the PowerShell command must be escaped as \".
See this answer for an explanation.
Since your /+ argument also contains embedded " chars., as part of the argument, you would have to escape them twice, namely as `\" (sic)

Docker run env variable does not work with single quotes?

I was running the following command:
docker run -e 'SOME_ENV_VARIABLE=somevalue' somecommand
And this did not pass the env variable to somecommand (Note: SOME_ENV_VARIABLE and somevalue did not have un-escaped single quotes, they were capital snake case and lowercase respectively without special character.
Later, I tried:
docker run -e "SOME_ENV_VARIABLE=somevalue" somecommand
And this somehow worked (note the double quotes).
Why is this? I have seen documentation with single quotes.
I tried this on Windows.
Quotation is handled by your shell - since you are on windows, that is cmd.exe. And, from what I understand, since cmd.exe does not handle single quotes, it will pass that argument with the quotes to docker.
It would work on Linux though (which usually has the bash shell), being the the environment many people would use docker on, and as such the reason it is present in a lot of documentation.

Grep with RegEx Inside a Docker Container?

Dipping my toes into Bash coding for the first time (not the most experienced person with Linux either) and I'm trying to read the version from the version.php inside a container at:
/config/www/nextcloud/version.php
To do so, I run:
docker exec -it 1c8c05daba19 grep -eo "(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?" /config/www/nextcloud/version.php
This uses a semantic versioning RegEx pattern (I know, a bit overkill, but it works for now) to read and extract the version from the line:
$OC_VersionString = '20.0.1';
However, when I run the command it tells me No such file or directory, (I've confirmed it does exist at that path inside the container) and then proceeds to spit out the entire contents of the file it just said doesn't exist?
grep: (0|[1-9]\d*).(0|[1-9]\d*).(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-])(?:.(?:0|[1-9]\d|\d*[a-zA-Z-][0-9a-zA-Z-]))))?(?:+([0-9a-zA-Z-]+(?:.[0-9a-zA-Z-]+)*))?: No such file or directory
/config/www/nextcloud/version.php:$OC_Version = array(20,0,1,1);
/config/www/nextcloud/version.php:$OC_VersionString = '20.0.1';
/config/www/nextcloud/version.php:$OC_Edition = '';
/config/www/nextcloud/version.php:$OC_VersionCanBeUpgradedFrom = array (
/config/www/nextcloud/version.php: 'nextcloud' =>
/config/www/nextcloud/version.php: 'owncloud' =>
/config/www/nextcloud/version.php:$vendor = 'nextcloud';
Anyone able to spot the problem?
Update 1:
For the sake of clarity, I'm trying to run this from a bash script. I just want to fetch the version number from that file, to use it in other areas of the script.
Update 2:
Responding to the comments, I tried to login to the container first, and then run the grep, and still get the same result. Then I cat that file and it shows it's contents no problem.
Many containers don't have the GNU versions of Unix tools and their various extensions. It's popular to base containers on Alpine Linux, which in turn uses a very lightweight single-binary tool called BusyBox to provide the base tools. Those tend to have the set of options required in the POSIX specs, and no more.
POSIX grep(1) in particular doesn't have an -o option. So the command you're running is
grep \
-eo \ # specify "o" as the regexp to match
"(regexps are write-only)" \ # a filename
/config/www/nextcloud/version.php # a second filename
Notice that the grep output in the interactive shell only contains lines with the letter "o", but not for example the line just containing array.
POSIX grep doesn't have an equivalent for GNU grep's -o option
Print only the matched (non-empty) parts of matching lines, with each such part on a separate output line. Output lines use the same delimiters as input....
but it's easy to do that with sed(1) instead. Ask it to match some stuff, the regexp in question, and some stuff, and replace it with the matched group.
sed -e 's/.*\(any regexp here\).*/\1/' input-file
(POSIX sed only accepts basic regular expressions, so you'll have to escape more of the parentheses.)
Well, for any potential future readers, I had no luck getting grep to do it, I'm sure it was my fault somehow and not grep's, but thanks to the help in this post I was able to use awk instead of grep, like so:
docker exec -it 1c8c05daba19 awk '/^\$OC_VersionString/ && match($0,/\047[0-9]+\.[0-9]+\.[0-9]+\047/){print substr($0,RSTART+1,RLENGTH-2)}' /config/www/nextcloud/version.php
That ended up doing exactly what I needed:
It logs into a docker container.
Scans and returns just the version number from the line I am looking for at: /config/www/nextcloud/version.php inside the container.
Exits stage left from the container with just the info I needed.
I can get right back to eating my Hot Cheetos.

Docker run errors on passing a dash as an argument?

I need to pass -Dfml.queryResult=confirm to the executable of an otherwise working docker container (on the docker run line), but all I get is : -Dfml.queryResult=confirm: invalid syntax ... I've tried with quotes, no quotes, single quotes, escaping it, everything I can think of, and I've put it behind -c as suggested here, but I always get an error. Am I missing something silly?

Ubuntu Cmake: Parse error in command line argument [duplicate]

-D CMAKE_C_COMPILER is what I use to choose my compiler. However, if I have CMake options that are turned on/off like USEIPHONEFLAG, I need to do -DUSEIPHONEFLAG=1, -D USEIPHONEFLAG=1 does not work. I was wondering how the space after -D works in CMake.
CMake's command line parsing is not very consistent or robust unfortunately.
This issue is probably down to the order in which you pass the arguments.
Internally, CMake iterates over the command line arguments twice. The first time it's looking for non-cache arguments and skips any beginning with -D. Any that don't fit into the list of proper args are assumed to be the path to the CMakeLists.txt file (or the directory, or the CMakeCache.txt).
It's assuming that there will be only one path passed, and does nothing to validate that assumption. Herein lies the problem. If you've passed -D Foo=1, then -D is seen as a complete argument and is skipped, and Foo=1 is seen as a path.
On the second iteration through the args, it now grabs the values given via -D, but on this run it correctly handles spaces after the -D. So it understands that -D Foo=1 is setting Foo to 1.
So, the position of the path in your command line is all-important here.
cmake -D Foo=1 MyProject/CMakeLists.txt # --> Works
cmake MyProject/CMakeLists.txt -D Foo=1 # --> Fails
To complicate things further, you can wrap the space in quotes and have CMake parse it, but the variable name then includes the space and is unusable in the CMakeLists file.
cmake MyProject/CMakeLists.txt "-D Foo=1" # --> Defines the unusable var ${ Foo}
Another inconsistency is that other command line flags work with or without a space (e.g. -G), and others require a space (e.g. -E).
My own advice would be to always avoid adding a space after the flag unless it's required. I guess always passing the path last would help too, although that shouldn't be required if you don't add extra spaces.

Resources