zshで変数をケース条件として使用する

zshで変数をケース条件として使用する

私の質問は、ここで尋ねられた質問に対応するzshです。変数をケース条件として使用するには?zshでは、ケースステートメントの条件として変数を使用したいと思います。たとえば、

input="foo"
pattern="(foo|bar)"

case $input in
$pattern)
    echo "you sent foo or bar"
;;
*)
    echo "foo or bar was not sent"
;;
esac

文字列を使用したいfooか、bar上記のコードで大文字と小文字のpattern条件を実行したいと思います。

ベストアンサー1

このコードをファイルとして保存した後first

pattern=fo*
input=foo
case $input in
$pattern)
   print T
   ;;
fo*)
   print NIL
   ;;
esac

-x変数は参照値として表示され、元の式は参照値として表示されないことがわかります。

% zsh -x first
+first:1> pattern='fo*'
+first:2> input=foo
+first:3> case foo (fo\*)
+first:3> case foo (fo*)
+first:8> print NIL
NIL

つまり、変数はリテラル文字列として扱われます。十分な時間を費やすと、zshexpn(1)グローバル交換フラグが実現します。

   ${~spec}
          Turn on the GLOB_SUBST option for the evaluation of spec; if the
          `~'  is  doubled,  turn  it  off.   When this option is set, the
          string resulting from the expansion will  be  interpreted  as  a
          pattern anywhere that is possible,

$patternしたがって、これを使用するように変更すると

pattern=fo*
input=foo
case $input in
$~pattern)                # !
   print T
   ;;
fo*)
   print NIL
   ;;
esac

私たちが見るもの

% zsh -x second
+second:1> pattern='fo*'
+second:2> input=foo
+second:3> case foo (fo*)
+second:5> print T
T

あなたの場合、スキーマを引用する必要があります。

pattern='(foo|bar)'
input=foo
case $input in
$~pattern)
   print T
   ;;
*)
   print NIL
   ;;
esac

おすすめ記事