0

I'm writing a php script that will execute a bash script on the server. The one thing that is absolutely required for this exercise is that we're using /var/tmp/count.sh to get my data.

bash script:

#!/bin/bash
#filename: /var/tmp/count.sh
cat /etc/passwd | grep ':201:' | awk -F ':' '{print $1}'
#This command will spit out:
# user1
# user2
# user3

PHP Script:

<?php
$output = shell_exec('/var/tmp/count.sh');
$sizeofme = sizeof($output);
echo "$output" . "\n" ;
echo "sizeofme = $sizeofme" . "\n" ;
// this spits out:
// user1
// user2
// user3
// sizeofme = 1
?>

How do I make a PHP array that contains 3 elements?

A PHP equivielant of the following bash for loop:

for i in ${output[@]; do
    newarray+=("$i")
done

Also, I noticed that if I do:

<?php
echo $output[0] . "\n" ;
echo $output[1] . "\n" ;
echo $output[2] . "\n" ;
echo $output[3] . "\n" ;
echo $output[4] . "\n" ;
echo $output[5] . "\n" ;
echo $output[6] . "\n" ;
echo $output[7] . "\n" ;
echo $output[8] . "\n" ;
echo $output[9] . "\n" ;
?>

I get:

u
s
e
r
1

u
s
e
r
2

... so on and so forth. What am I overlooking?

parsecpython
  • 585
  • 2
  • 6
  • 17
  • 1
    The reason it's outputting like that is that you can treat a string as an array and get a single character back. – Machavity Jul 19 '16 at 21:49

1 Answers1

1

I think PHP is treating the return as one contiguous string. Try the following

$data = explode("\n", $output);
var_dump($data);

That should give you the array you want

Machavity
  • 30,841
  • 27
  • 92
  • 100
  • Related SO question: [how to iterate over a string line by line](http://stackoverflow.com/questions/1462720/iterate-over-each-line-in-a-string-in-php). `explode` is more concise, +1 – Juan Tomas Jul 19 '16 at 21:52
  • This is good. it's working like I expect. One issue though: the last entry is a newline: `[3]=> string(0) ""` I'll work on trimming it out but thanks, this is good – parsecpython Jul 19 '16 at 22:21
  • `$data = explode("\n", $output);` `$data2 = array_pop($data);` – parsecpython Jul 20 '16 at 15:19