简体   繁体   中英

How to pass awk output into bash variable?

#!/bin/bash

function init(){

   echo $(\

      ps -aef | \
      awk -v var=$1 -d 'm=/var/{ if ($3 == 1)  print $2 }\
      END{ if(!m)  print 0 }' \

   )
}

//Always return 0 instead PID
MyVar=`init nginx`

When these command is not wrap in function it works correctly

Corrective (about what this code must do): these code snippet is a draft of my script for startup/reboot/stop nginx+mysql-server+php-fpm . When script receive "start" command , function init() must decide : is server whether running ? If init() returns value != 0 , this means that server already running

PS I am very grateful for your answers I hope they will be useful

  1. Your test case does not work as stated:

    • It uses // for a comments (not # )
    • The test never outputs anything - hence it cannot output 0
    • If you call this script from somewhere else it will always return 0 as that is the status of the last command. In that case you can add exit 1 to the last line of your script to test.
  2. You do not state what you are trying to accomplish. My guees would be that you want the PID of nginx. For that you should simply use pgrep nginx rather than a complicated awk script.

  3. It probably returns 0 because of if(!m) print 0 . But we do not have the full picture.

  4. You must be using gawk. Your awk script is rather verbose when run on BSD. And as you do not explain what the intention is I can only guess you want the PID.

  5. You do not need the echo it is superfluous

  6. You can use both backticks `` and $() to put output into a variable

This script will return the PID for the first parameter:

#!/usr/local/bin/bash
function init(){
  pgrep $1
}
MyVar=`init $1`
echo Result: $MyVar

This script will numerate lines using awk. Enter filename as first parameter:

#!/usr/local/bin/bash
function init(){
  cat $1 | awk '{printf("%5d : %s\n", NR,$0)}'
}
MyVar=$(init $1)
echo Result: $MyVar

Change #! to match your location of bash.

Your script has several pointless levels of indirection, this works fine to save output to a variable:

variable=$( ps -aef | awk  '{ /* awk script */ }' )

You don't need the shell function, you definitely don't need to re- echo the output, but you do need to fix your awk script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM