Can we use PHP in Bash Script?

后端 未结 3 1908
攒了一身酷
攒了一身酷 2021-01-29 08:37

I have a bash script abcd.sh

#!/bin/sh
for i in `seq 8`; do ssh w$i \'uptime;ps -elf|grep httpd|wc -l;free -m;mpstat\'; done &
pid=$!
sleep 1
ki         


        
相关标签:
3条回答
  • 2021-01-29 08:49

    Mmm, if you are using bash, you should maybe use a bash shebang on line 1 so people know you are expecting bash features to be available. And if you are using bash, you can use a bash sequence anyway:

    #!/bin/bash
    for i in {1..8}; do echo $i; done
    

    Update 1

    If the number of servers is obtained through PHP, you can do something like this:

    numservers=$(php -r 'echo 8;')
    for i in $(seq $numservers); do echo $i; done
    1
    2
    3
    4
    5
    6
    7
    8
    

    Update 2

    Ok, you said the number of servers is dynamic, but then you say it is set in the script (which seems contradictory), but this is what you do:

    numservers=10
    for i in $(seq $numservers); do echo $i; done
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    0 讨论(0)
  • 2021-01-29 08:50

    Why don't you write the entire shell script in PHP?

    #!/usr/bin/php
    <?php
    for ($i = 0; $i < 8; $i++) {
        exec("ssh w$i 'uptime;ps -elf|grep httpd|wc -l;free -m;mpstat'");
    }
    ?>
    

    (code is untested, just an example)

    0 讨论(0)
  • 2021-01-29 08:51

    It's not easy to understand what you want.

    Maybe this helps. The script defines a var PHP_VAR in bash and use this var in PHP. Then we call a PHP code snippet an put the output in the shell var output. At last we output the var output (but you can do something else with it).

    Attation: All the output from the PHP will be found in the var output.

    #!/bin/bash
    
    echo "I am a bash echo"
    
    export PHP_VAR="I was in php"
    # Here we start php and put the output in 'output'
    output=$(php << EOF
       <?php \$inner_var = getenv("PHP_VAR");
       echo \$inner_var; ?>
    EOF
    )
    
    # usage var 'output' with php output
    echo "---$output---"
    
    0 讨论(0)
提交回复
热议问题