It may help if you are on a Mac and use TextMate, though not entirely necessary.
My php location:
$which php
/opt/local/bin/php
The script:
#!/opt/local/bin/php
<?php
shell_exec("echo -n 'my-string' > out.txt");
?>
The -n to echo suppress the newline that is automatically added to all shell echo commands.
If I run the above php code from the shell:
chmod u+x myfile.php
./myfile.php
I end up with 'out.txt', the contents of which being:
-n my-string
If I run the exact same code within TextMate, the contents of 'out.txt' will be correct:
my-string
I can't figures out what php is up to with putting the literal string '-n' in the output. I really wonder why TextMate does the correct thing. I have checked that both are using the same php, php -i shows mostly the same stuff, of course there are differences as one is run within TextMate, the other in the shell, so one output has pointers to the file whereas the other doesn't. As far as I can tell, $PATH and $ENV are the same.
I have tried a handful of different methods to work around this none of which are working. I actually will not be able to use a workaround, as this has been distilled down to a simple case for posting to SO. My use case for this pipes to pbcopy, which I believed was a Mac OS X only feature, so I used >> redirection here because that is universal.
Ultimately, I want a result on my clipboard that does not have a trailing newline, which is dangerous as pasting that in a shell will execute whatever preceded it.
Thanks
Is it possible that php is calling a different echo than your shell built in echo? Many versions of echo do not support -n and will output it as part of your string.
You could try shell_exec("which echo"); to find out which it is running.
Note that printf will not display the new line unless you explicitly add it. So you can use which printf to figure out where this resides and call it instead.
shell_exec("/usr/local/bin/printf '%s' 'mystring' > out.txt");
PHP just defers the call to popen in Unix platforms. See the manual page for Mac OS X:
The command argument is a pointer to a null-terminated string containing a shell command line. This
command is passed to /bin/sh, using the -c flag; interpretation, if any, is performed by the shell.
So it should be the same as running /bin/sh -c "echo -n 'my-string' > out.txt"
Related
I want to run two commands in a Windows CMD console.
In Linux I would do it like this
touch thisfile ; ls -lstrh
How is it done on Windows?
Like this on all Microsoft OSes since 2000, and still good today:
dir & echo foo
If you want the second command to execute only if the first exited successfully:
dir && echo foo
The single ampersand (&) syntax to execute multiple commands on one line goes back to Windows XP, Windows 2000, and some earlier NT versions. (4.0 at least, according to one commenter here.)
There are quite a few other points about this that you'll find scrolling down this page.
Historical data follows, for those who may find it educational.
Prior to that, the && syntax was only a feature of the shell replacement 4DOS before that feature was added to the Microsoft command interpreter.
In Windows 95, 98 and ME, you'd use the pipe character instead:
dir | echo foo
In MS-DOS 5.0 and later, through some earlier Windows and NT versions of the command interpreter, the (undocumented) command separator was character 20 (Ctrl+T) which I'll represent with ^T here.
dir ^T echo foo
A quote from the documentation:
Source: Microsoft, Windows XP Professional Product Documentation, Command shell overview
Also: An A-Z Index of Windows CMD commands
Using multiple commands and conditional processing symbols
You can run multiple commands from a single command line or script using conditional processing symbols. When you run multiple commands with conditional processing symbols, the commands to the right of the conditional processing symbol act based upon the results of the command to the left of the conditional processing symbol.
For example, you might want to run a command only if the previous command fails. Or, you might want to run a command only if the previous command is successful.
You can use the special characters listed in the following table to pass multiple commands.
& [...]
command1 & command2
Use to separate multiple commands on one command line. Cmd.exe runs the first command, and then the second command.
&& [...]
command1 && command2
Use to run the command following && only if the command preceding the symbol is successful. Cmd.exe runs the first command, and then runs the second command only if the first command completed successfully.
|| [...]
command1 || command2
Use to run the command following || only if the command preceding || fails. Cmd.exe runs the first command, and then runs the second command only if the first command did not complete successfully (receives an error code greater than zero).
( ) [...]
(command1 & command2)
Use to group or nest multiple commands.
; or ,
command1 parameter1;parameter2
Use to separate command parameters.
& is the Bash equivalent for ; ( run commands) and && is the Bash equivalent of && (run commands only when the previous has not caused an error).
If you want to create a cmd shortcut (for example on your desktop) add /k parameter (/k means keep, /c will close window):
cmd /k echo hello && cd c:\ && cd Windows
You can use & to run commands one after another. Example: c:\dir & vim myFile.txt
You can use call to overcome the problem of environment variables being evaluated too soon - e.g.
set A=Hello & call echo %A%
A number of processing symbols can be used when running several commands on the same line, and may lead to processing redirection in some cases, altering output in other case, or just fail. One important case is placing on the same line commands that manipulate variables.
#echo off
setlocal enabledelayedexpansion
set count=0
set "count=1" & echo %count% !count!
0 1
As you see in the above example, when commands using variables are placed on the same line, you must use delayed expansion to update your variable values. If your variable is indexed, use CALL command with %% modifiers to update its value on the same line:
set "i=5" & set "arg!i!=MyFile!i!" & call echo path!i!=%temp%\%%arg!i!%%
path5=C:\Users\UserName\AppData\Local\Temp\MyFile5
cmd /c ipconfig /all & Output.txt
This command execute command and open Output.txt file in a single command
So, I was trying to enable the specific task of running RegAsm (register assembly) from a context menu. The issue I had was that the result would flash up and go away before I could read it. So I tried piping to Pause, which does not work when the command fails (as mentioned here Pause command not working in .bat script and here Batch file command PAUSE does not work). So I tried cmd /k but that leaves the window open for more commands (I just want to read the result). So I added a pause followed by exit to the chain, resulting in the following:
cmd /k C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe "%1" /codebase \"%1\" & pause & exit
This works like a charm -- RegAsm runs on the file and shows its results, then a "Press any key to continue..." prompt is shown, then the command prompt window closes when a key is pressed.
P.S. For others who might be interested, you can use the following .reg file entries to add a dllfile association to .dll files and then a RegAsm command extension to that (notice the escaped quotes and backslashes):
[HKEY_CLASSES_ROOT\.dll]
"Content Type"="application/x-msdownload"
#="dllfile"
[HKEY_CLASSES_ROOT\dllfile]
#="Application Extension"
[HKEY_CLASSES_ROOT\dllfile\Shell\RegAsm]
#="Register Assembly"
[HKEY_CLASSES_ROOT\dllfile\Shell\RegAsm\command]
#="cmd /k C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\regasm.exe \"%1\" /codebase \"%1\" & pause & exit"
Now I have a nice right-click menu to register an assembly.
In windows, I used all the above solutions &, && but nothing worked
Finally ';' symbol worked for me
npm install; npm start
Well, you have two options: Piping, or just &:
DIR /S & START FILE.TXT
Or,
tasklist | find "notepad.exe"
Piping (|) is more for taking the output of one command, and putting it into another. And (&) is just saying run this, and that.
In order to execute two commands at the same time, you must put an & (ampersand) symbol between the two commands. Like so:
color 0a & start chrome.exe
Cheers!
I try to have two pings in the same window, and it is a serial command on the same line. After finishing the first, run the second command.
The solution was to combine with start /b on a Windows 7 command prompt.
Start as usual, without /b, and launch in a separate window.
The command used to launch in the same line is:
start /b command1 parameters & command2 parameters
Any way, if you wish to parse the output, I don't recommend to use this.
I noticed the output is scrambled between the output of the commands.
Use & symbol in windows to use command in one line
C:\Users\Arshdeep Singh>cd Desktop\PROJECTS\PYTHON\programiz & jupyter notebook
like in linux
we use,
touch thisfile ; ls -lstrh
I was trying to create batch file to start elevated cmd and to make it run 2 separate commands.
When I used & or && characters, I got a problem. For instance, this is the text in my batch file:
powershell.exe -Command "Start-Process cmd \"/k echo hello && call cd C:\ \" -Verb RunAs"
I get parse error:
After several guesses I found out, that if you surround && with quotes like "&&" it works:
powershell.exe -Command "Start-Process cmd \"/k echo hello "&&" call cd C:\ \" -Verb RunAs"
And here's the result:
May be this'll help someone :)
No, cd / && tree && echo %time%. The time echoed is at when the first command is executed.
The piping has some issue, but it is not critical as long as people know how it works.
One more example: For example, when we use the gulp build system, instead of
gulp - default > build
gulp build - build build-folder
gulp watch - start file-watch
gulp dist - build dist-folder
We can do that with one line:
cd c:\xampp\htdocs\project & gulp & gulp watch
Yes there is. It's &.
&& will execute command 2 when command 1 is complete providing it didn't fail.
& will execute regardless.
With windows 10 you can also use scriptrunner:
ScriptRunner.exe -appvscript demoA.cmd arg1 arg2 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror -appvscript demoB.ps1 arg3 arg4 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror
it allows you to start few commands on one line you want you can run them consecutive or without waiting each other, you can put timeouts and rollback on error.
Try to create a .bat ot .cmd file with those lines using doskey key and $T which is equivalent to & to do several command line in just one line :
touch=echo off $T echo. ^> $* $T dir /B $T echo on
It'll create an empty file.
Example:
touch myfile
In cmd you'll get something like this:
But as mentioned previously by others, it is really advised to use & operator to do many command line in one line from CMD prompt.
Enjoy =)
When you try to use or manipulate variables in one line beware of their content! E.g. a variable like the following
PATH=C:\Program Files (x86)\somewhere;"C:\Company\Cool Tool";%USERPROFILE%\AppData\Local\Microsoft\WindowsApps;
may lead to a lot of unhand-able trouble if you use it as %PATH%
The closing parentheses terminate your group statement
The double quotes don't allow you to use %PATH% to handle the parentheses problem
And what will a referenced variable like %USERPROFILE% contain?
It's simple: just differentiate them with && signs.
Example:
echo "Hello World" && echo "GoodBye World".
"Goodbye World" will be printed after "Hello World".
How can I force the php exec() to interpret the linux brace expansion?
I am encountering a strange behavior, and did not find a way to fix it the way I want.
I want to execute a linux command containing brace expression to select a batch of files,
from php
I am using php to generate a "random" number of files, and want then to execute a shell script which will make something with the files.
Here is my bash version:
"$ echo $BASH_VERSION"
4.1.5(1)-release
To give a simple example, let's assume I create the following files:
touch /tmp/file_{1..12}.xml
shell.sh
#!/bin/sh
FILES=$*
echo "\n\nFILES: $FILES"
for f in $FILES; do
echo Posting file $f
done
test.php
<?php
$cmd = "./shell.sh /tmp/file_{1..12}.xml";
echo"\n\nCOMMAND:\n".$cmd."\n\n";
var_dump(shell_exec($cmd));
The output of "php test.php" is:
COMMAND:
./shell.sh /tmp/file_{1..12}.xml
string(66) "
FILES: /tmp/file_{1..12}.xml
Posting file /tmp/file_{1..12}.xml
"
I expect to have the same as if I run "./shell.sh /tmp/file_{1..12}.xml" from linux terminal:
$ ./shell.sh /tmp/file_{1..12}.xml
FILES: /tmp/file_1.xml /tmp/file_2.xml /tmp/file_3.xml /tmp/file_4.xml /tmp/file_5.xml /tmp/file_6.xml /tmp/file_7.xml /tmp/file_8.xml /tmp/file_9.xml /tmp/file_10.xml /tmp/file_11.xml /tmp/file_12.xml
Posting file /tmp/file_1.xml
Posting file /tmp/file_2.xml
Posting file /tmp/file_3.xml
Posting file /tmp/file_4.xml
Posting file /tmp/file_5.xml
Posting file /tmp/file_6.xml
Posting file /tmp/file_7.xml
Posting file /tmp/file_8.xml
Posting file /tmp/file_9.xml
Posting file /tmp/file_10.xml
Posting file /tmp/file_11.xml
Posting file /tmp/file_12.xml
But I also tried with or without escapeshellcmd()
with exec($cmd) AND other functions like system() or eval()...
None of them did the job...
I know that I could do the foreach loop in php, but I am sure there is a way to have this command interpreted as if it was launched from command line.
As #Josh Trii Johnston has pointed out, the 'outer' shell you are implicitly using to call your shell script using shell_exec() is probably not Bash in your case. This way, brace expansion never takes place because there is no shell capable of expanding the expression before calling your program (as it would be in an interactive Bash session).
You could
try to change the shell invoked by PHP's shell_exec(), but this may not be possible
call /bin/bash with your program and the brace expression instead of only the brace expression: $cmd = "/bin/bash -c './shell.sh /tmp/file_{1..12}.xml'";
use eval on the argument inside your script to expand the brace expression.
From the bash(1) man page:
If bash is invoked with the name sh, it tries to mimic the startup behavior of historical versions of sh as closely as possible, while conforming to the POSIX standard as well. [...] When invoked as sh, bash enters posix mode after the startup files are read.
Try changing
#!/bin/sh
to
#!/bin/bash
if you expect Bash behavior (there is no brace expansion in POSIX).
If all of the above does not help, you should make sure that brace expansion is activated by executing set -o (while calling your program from the PHP script). If it is off, you can turn it on using:
set -o braceexpand
I used your exact example on my OS X machine and it works as expected. What user are you executing php as? Is that user's shell (/bin/sh) set to a non-bash shell?
$ php test.php
COMMAND:
./shell.sh /tmp/file_{1..12}.xml
string(555) "\n\nFILES: /tmp/file_1.xml /tmp/file_2.xml /tmp/file_3.xml /tmp/file_4.xml /tmp/file_5.xml /tmp/file_6.xml /tmp/file_7.xml /tmp/file_8.xml /tmp/file_9.xml /tmp/file_10.xml /tmp/file_11.xml /tmp/file_12.xml\nPosting file /tmp/file_1.xml\nPosting file /tmp/file_2.xml\nPosting file /tmp/file_3.xml\nPosting file /tmp/file_4.xml\nPosting file /tmp/file_5.xml\nPosting file /tmp/file_6.xml\nPosting file /tmp/file_7.xml\nPosting file /tmp/file_8.xml\nPosting file /tmp/file_9.xml\nPosting file /tmp/file_10.xml\nPost"...
I have to design a interface using PHP for a software written in python. Currently this software is used from command line by passing input, mostly the input is a text file. There are series of steps and for every step a python script is called. Every step takes a text file as input and an generates an output text file in the folder decided by the user. I am using system() of php but I can't see the output but when I use the same command from command line it generates the output. Example of command :
python /software/qiime-1.4.0-release/bin/check_id_map.py -m /home/qiime/sample/Fasting_Map.txt -o /home/qiime/sample/mapping_output -v
try this
$script = 'software/qiime-1.4.0-release/bin/check_id_map.py -m /home/qiime/sample/Fasting_Map.txt -o /home/qiime/sample/mapping_output -v';
$a = exec($script);
If you are not on windows, have you tried adding 2>&1 (redirect stderr to stdout) to the end of the command?
$output = system("python /software/qiime-1.4.0-release/bin/check_id_map.py -m /home/qiime/sample/Fasting_Map.txt -o /home/qiime/sample/mapping_output -v 2>&1", $exitcode);
Found from http://www.php.net/manual/en/function.system.php#108713
Also the doc says that it
Returns the last line of the command output on success, and FALSE on
failure.
So if you are trying to get multiple lines, you may need to redirect it to a file and read that in.
instead of system() try surrounding the code in `ticks`...
It has a similar functionality but behaves a little differently in the way it returns the output..
I am using PHP on Windows machin. I also use Dev C++. I can perfectly compile .cpp file on CMD using this command:
g++ hello.cpp -O3 -o hello.exe
Now what I am trying to do is running the same command using php system() function, so it looks like this:
system("g++ c:\wamp\www\grader\hello.cpp -O3 -o C:\wamp\www\grader\hello.exe");
but it doesn't compile. I am lost, please tell me what am I missing?
I also looked up at this question and thats exactly what I need, but I couldnt find a usefull solution for my case there:
Php script to compile c++ file and run the executable file with input file
Use the PHP exec command.
echo exec('g++ hello.cpp -O3 -o hello.exe');
should work.
There's a whole family of different exec & system commands in PHP, see here:
http://www.php.net/manual/en/ref.exec.php
If you want the output into a variable, then use :
$variable = exec('g++ hello.cpp -O3 -o hello.exe');
If that doesn't work, then make sure that g++ is available in your path, and that your logged in with sufficient enough privliges to allow it to execute.
You may find also that it's failing beacuse PHP is essentially being executed by your web server (Unless your also running PHP from the cmd prompt) , and the web server user ID may not have write access to the folder where G++ is trying to create the output file.
Temporarily granting write access to 'Everybody' on the output folder will verify if that is the case.
Two things:
You are using double quotes and are not escaping the \ inside the path.
You are not using a full path to g++.
The first one is important as \ followed by something has a special meaning in such a string (you might know \n as new line), the second one is relevant since the PHP environment might have a different search path.
A solution might be
system("c:\\path\\to\\g++ c:\\wamp\\www\\grader\\hello.cpp -O3 -o C:\\wamp\\www\\grader\\hello.exe");
Alternatively you can use single quotes, intead of double quotes, they use diffeent,less strict escaping rules
system('c:\path\to\g++ c:\wamp\www\grader\hello.cpp -O3 -o C:\wamp\www\grader\hello.exe');
or use / instead of \, which is supported by windows, too.
system("c:/path/to/g++ c:/wamp/www/grader/hello.cpp -O3 -o C:/wamp/www/grader/hello.exe");
What you do is your choice, while many might consider the first one as ugly, and the last one as bad style on Windows ;-)
Thanks to everyone. I tried to run the codes given in above posts and it worked like a charm.
I ran the following code using my browser
$var = exec("g++ C:/wamp/www/cpp/hello.cpp -O3 -o C:/wamp/www/cpp/hello.exe");
echo $var;
The exe file is created. I am able to see the result when i run the exe file but the problem is when i run the above code in the browser, the result is not displayed on the webpage. I gave full access permission to all users but still give does not show the result on the webpage.
I really need help on this since i am doing a project on simulated annealing where i want to get the result from compiled c++ program and display it in the webpage with some jquery highcharts.
Thanks again to all, it has helped me alot and i have learnt alot as well.
In a previous post, I was trying to update the encoding for a download file from php. One of the suggestions was to run the unix2dos command before sending the file to the user. This works great when I run the command on the linux box, but when I try and run the command from php I get nothing. Here is what I tried:
$cmd = "unix2dos -n $fullPath $downloadFile";
echo exec($cmd, $out, $retVal);
This displays nothing to the screen, $retVal is 0, and $out is an empty string.
echo system($cmd, $retVal);
This displays nothing to the screen, $retVal is 0.
echo shell_exec($cmd);
This displays nothing to the screen.
I have also tried escaping the command and it parameters like:
$cmd = escapeshellcmd($cmd);
and
$cmd = "unix2dos ". escapeshellarg("-n \"$fullPath\" \"$downloadFile\"");
Please let me know if you see something that I am doing wrong.
Thanks!
Edit: Here is some info that may be helpful.
unix2dos version: 2.2 (1995.03.31)
php version 5.2.9
Running in apache 2 on in Redhat Enterprise Linux 4
Have you considered a pure PHP solution?
<?php
$unixfile = file_get_content('/location/of/file/');
$dosfile= str_replace("\n", "\r\n", $unixfile );
file_put_contents('/location/of/file/', $dosfile);
?>
Something like that should do it, although untested :)
Shadi
See which user the PHP exec command is running as:
<?php system('whoami'); ?>
If this command fails then you likely do not have permission to use exec() or system(), so check your INI files. But be sure to check the correct ones! On Debian systems there are separate Apache and CLI INI files stored at /etc/php5/apache/php.ini and /etc/php5/cli/php.ini respectively. Sorry I do not know the locations for RedHat.
If the whoami command succeeds, make sure that the unix2dos command can be run by the user that is shown, and that the same user is allowed to make changes to the files in question by using chmod or chown.
Are you using the full path to unix2dos? Perhaps the executable is in your path for your shell but not in the path that PHP is using.
My implementation of unix2dos produces no output. If the return value is 0 then the command succeeded and your file has been updated.
The only other thing I see is the -n option which my version doesn't seem to have. You should probably check your man page to see what options it supports
unix2dos does not display the file it converts. Therefor you must display it yourself. A very basic way to do it could be :
$cmd = "unix2dos -n $fullPath $downloadFile";
echo exec($cmd, $out, $retVal);
include "$fullPath."/".$downloadFile;
Using include is pretty dirty but quick and easy. A cleaner way would be to use fopen and read the file then display it.
You'd better create a function that enclose all the operation : conversion + display so you'll have everything at hands.
But, If I were you, I'd prefer to not use exec at all and use FileIterator with a trim on every line so you will not have to care about the carriage return nor deal with a hazardous shell binding.
Not sure about your exact problem, but debugging suggestion:
Try first setting $cmd to ls. See if that works. Then try using /bin/ls (use the full path.)
If those don't work, then there might be a problem with your PHP configuration - there might be a safemode parameter or something which disallows the use of exec(), shell_exec(), or system() functions.
I got the source code from here.
http://www.sfr-fresh.com/linux/misc/unix2dos-2.2.src.tar.gz
I compiled it and then ran the tool. This was my output:
rascher#danish:~/unix2dos$ ./a.out -n 1.txt 2.txt
unix2dos: converting file 1.txt to file 2.txt in DOS format ...
I think the problem is this: the program writes all of its output to stderr, rather than stdout. If you look at the source code, you can see "fprintf(stderr, ...)"
As far as I know, PHP will only read the part of your program's output that is sent to STDOUT. So to overcome this, it seems like you have to redirect the output of your program (unix2dos uses stderr) to stdout. To do this, try something like:
$cmd = "unix2dos -n $fullPath $downloadFile 2>&1"
The "2>" means "redirect stderr" and "&1" means "to stdout".
In either case, I would imagine that the file was converting properly, but since you weren't getting any of the expected output, you thought it was failing. Before making the change, check on the output file to see if it is in DOS or UNIX format.