符合 if 語句中以 -(破折號)開頭的全域模式

符合 if 語句中以 -(破折號)開頭的全域模式

我無法匹配 if 語句中的“--debug”。
我的目標是符合 POSIX 標準的腳本。

CHANNELS=;
set -- stable beta dev master --debug

echo "DEBUG: Before while $@";
while [ $# -gt 0  ]; do
  echo "DEBUG: Inside while $1";
  if [ ! $1 = -* ]; then
    echo "DEBUG: Inside if $1";
    CHANNELS="$CHANNELS $1";
  fi
  shift;
done
echo "DEBUG: After while $CHANNELS";

實際 -> $CHANNELS 具有“stable beta dev master --debug”
預期 -> $CHANNELS 應具有“stable beta dev master”

答案1

模式匹配是透過casePOSIX shell 中的構造完成的:

CHANNELS=
set -- stable beta dev master --debug

echo "DEBUG: Before while $@";
while [ "$#" -gt 0  ]; do
  echo "DEBUG: Inside while $1";
  case $1 in
    (-*) ;;
    (*)
      echo "DEBUG: Inside case (*)"
      CHANNELS="$CHANNELS $1";;
  esac
  shift
done
echo "DEBUG: After while $CHANNELS";

相關內容