複数の変数を含む複合変数の拡張

複数の変数を含む複合変数の拡張

次の5つの変数があります。

drt="/var/www/html"

drt_chown="chown -R www-data:www-data ${drt}/"
drt_chmod="chmod -R a-x,a=rX,u+w ${drt}/"
rss="systemctl restart nginx.service"
rpf="/etc/init.d/php*-fpm restart"

私は最後の4つの変数を結合/接続/追加しようとしています。複合変数rse一度に簡単に拡張できるように名前を付けました。

rse="${drt_chown} ; ${drt_chmod} ; ${rss} ; ${rpf}"

その後、拡張しようとしていますrse

${rse}

残念ながら、この拡張は次のrseエラーによって失敗します。

chown: cannot access ';': No such file or directory
chown: cannot access 'chmod': No such file or directory
chown: cannot access 'a-x,a=rX,u+w': No such file or directory
chown: cannot access ';': No such file or directory
chown: cannot access 'systemctl': No such file or directory
chown: cannot access 'restart': No such file or directory
chown: cannot access 'nginx.service': No such file or directory
chown: cannot access ';': No such file or directory
chown: cannot access 'restart': No such file or directory

私の質問は、複合変数を拡張する正確で最も短い方法は何ですか?それとも、少なくとも最良の選択は何だと思いますか?

側面仕事私にとって非常に重要です。


メモ:

1. 現在の質問は、次の質問に対する後続の質問です。この問題、誤って質問しました(実際に現在の質問を聞きたかったからです)。

2. Googleキーワード(タグでは不可能):ホスト変数/メガ変数または変数を拡張する変数。

ベストアンサー1

変数をリンクすることは問題ではありません。どちらの割り当てもrse文字列の連結に問題はありません。問題は前の問題と同じです。;and &&(and &and |andなど)などの>特殊演算子は、変数拡張後に解釈されません。"

つまり、ここにはリダイレクトや条件はなく、文字列内の変数拡張(ある種の文字列連結)のみがあります。引用符cmdも特別ではありません。

$ cmd1='echo "foo" > bar'
$ cmd2='echo "false"'
$ cmd="$cmd1 || $cmd2"
$ $cmd
"foo" > bar || echo "false"

代わりに関数を使用する必要があります。

drt="/var/www/html"
drt_chown() { chown -R www-data:www-data "${drt}/"; }

その後、他のコマンドのように実行し、を使用すると、drt_chown変数の現在の値が適用されますdrt

より良い方法は、関数にパラメータを受け入れさせることです。

www_chown() { chown -R www-data:www-data "$1"; }

www_chown /var/www/html

その後、必要に応じて別の関数を呼び出す関数を作成できます。

doitall() {
    drt_chown &&
    drt_chmod &&
    ...
}

おすすめ記事