関数引数が提供するコマンドを実行します。

関数引数が提供するコマンドを実行します。

引数としてメソッドに与えられたコマンドを実行するbashスクリプトから関数メソッドを作成しようとしています。

これは次のことを意味します。

special_execute()
{
    # Some code

    # Here's the point where the command gets executed
    $@

    # More code
}

special_execute echo "abc"

これを試しましたが、$@どうすればいいですか?"$@"$*"$*"

ベストアンサー1

私は関数に引数を渡すときの参照問題だけだと思います。

次のように呼び出してみてください。

$ special_execute "echo 'abc'"
'abc'

一重引用符を使用したくない場合は、abc次のように引用符を変更してください。

$ special_execute "echo abc"
abc

デバッグ

より詳細な方法で再エコーされるように関数の内部構造をラップできます。

$ function special_execute() { set -x; "$@"; set +x; }

その後、関数を介してコマンドを実行すると、special_execute何が起こるかを確認できます。

PS:はい:

$ special_execute ps -eaf
+ ps -eaf
UID        PID  PPID  C STIME TTY          TIME CMD
root         1     0  0 Aug21 ?        00:00:01 /sbin/init
root         2     0  0 Aug21 ?        00:00:00 [kthreadd]
...

真珠の例:

$ special_execute perl -MTime::HiRes=sleep -le 'for(1..10) { print; sleep 0.05; }'
+ perl -MTime::HiRes=sleep -le 'for(1..10) { print; sleep 0.05; }'
1
2
3
4
5
6
7
8
9
10
+ set +x

パラメータの解析$1

に渡された引数の解析と同様の操作を実行できます$1

$ function special_execute() { 
    [ "$1" -eq "-123" ] && echo "flagY" || echo "flagN"; 
    shift; 
    set -x; "$@"; set +x; 
  }

はい

デバッグを有効にする:

$ special_execute -123 perl -MTime::HiRes=sleep -le 'for(1..5) { print; sleep 0.05; }'
flagY
+ perl -MTime::HiRes=sleep -le 'for(1..5) { print; sleep 0.05; }'
1
2
3
4
5
+ set +x

デバッグオフ - -123:

$ special_execute -123 perl -MTime::HiRes=sleep -le 'for(1..5) { print; sleep 0.05; }'
flagY
1
2
3
4
5

デバッグオフ - -456:

$ special_execute -456 perl -MTime::HiRes=sleep -le 'for(1..5) { print; sleep 0.05; }'
flagN
1
2
3
4
5

おすすめ記事