2016-10-12 5 views
0

Ich versuche, mit zu machen war zu unterscheiden, seine in TerminalBash: function-Wrapper für andere Funktionen Funktion mit Rohr als Argument für eine andere Funktion

red_line="$(tput setaf 1)## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## $(tput sgr 0)" 

function wrapper { 
    echo $red_line; 
    echo "$(tput setaf 1)## $(tput setab 7)$(tput setaf 0)$1 $(tput sgr 0)"; 
    $2; 
    echo $red_line; 
} 

function foo { 
    wrapper "custom command description" "ps axo pid,stat,pcpu,comm | tail -n 10;" 
} 

aber Fehler ist aufgetreten: ps: illegal argument: |

I‘ $(ps ... | tail -n 10) und Backticks habe versucht, statt Zeichenfolge zu verwenden und dann mit echo $2 Ergebnis in Wrapper ausdrucken, aber gefangen weiteren Fehler

versuchte auch "eval $(ps ... | tail -n 10)" und es hat auch nicht funktioniert.

Alles funktioniert gut w/o-Wrapper:

function pss { 
    echo $red_line 
    echo "$(tput setaf 1)## $(tput setab 7)$(tput setaf 0)formatted 'ps ax' command $(tput sgr 0)" 

    ps axo pid,stat,pcpu,comm | tail -n $1; 

    echo $red_line 
} 

result screenshot

+3

[Ich versuche, einen Befehl zu setzen in einer Variablen, aber die komplexen Fälle scheitern immer!] (http://mywiki.wooledge.org/BashFAQ/050) – chepner

Antwort

1

Tnx @chepner für aufgerufene Beitrag über komplexe Befehle als Argument übergeben. Aber das eigentliche Problem war mit Unordnung mit doppelten Anführungszeichen in Funktionen Argumente in echo und wrapper.

Korrekter Code:

red_line="$(tput setaf 1)## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## $(tput sgr 0)" 

function wrapper { 
    echo $red_line; 
    echo "$(tput setaf 1)## $(tput setab 7)$(tput setaf 0)$1 $(tput sgr 0)"; 
    echo "$2"; 
    echo $red_line; 
} 

function pss { 
    res="$(ps axo pid,stat,pcpu,comm | tail -n $1)" 
    wrapper "custom command description" "$res" 
    # also work: 
    # wrapper "custom command description" "$(ps axo pid,stat,pcpu,comm | tail -n $1)" 
} 
1

Aiven Lebowski ‚s Antwort ist richtig. aber wenn Sie wirklich halten foo wollte wie er ist und $ 2 an Ort und Stelle durchführen, wo Sie es ausdrückte, brauchte man nur eval zu tun

red_line="$(tput setaf 1)## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## $(tput sgr 0)" 

function wrapper { 
    echo $red_line; 
    echo "$(tput setaf 1)## $(tput setab 7)$(tput setaf 0)$1 $(tput sgr 0)"; 
    eval $2 
    echo $red_line; 
} 

function foo { 
    wrapper "custom command description" "ps axo pid,stat,pcpu,comm | tail -n 10;" 
} 

Ich hoffe, das hilft

Verwandte Themen