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?

1
  • 1
    The reason it's outputting like that is that you can treat a string as an array and get a single character back. Commented Jul 19, 2016 at 21:49

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Related SO question: how to iterate over a string line by line. explode is more concise, +1
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
$data = explode("\n", $output); $data2 = array_pop($data);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.