shell 测试运算符正则表达式

san*_*ika 4 regex shell

#!/bin/bash
# This file will fix the cygwin vs linux paths and load programmer's notepad under windows.
# mail : <sandundhammikaperera@gmail.com> 
# invokes the GNU GPL, all rights are granted.


# check first parameter is non empty.
# if empty then give a error message and exit.
file=${1:?"Usage: pn filename"};

if [[ "$file" == /*/* ]] ;then
  #if long directory name.
# :FAILTHROUGH:
  echo "$0: Executing pn.exe $file" 

else 
  file="$(pwd)/$file";
fi

#check whether the filename starts with / if so replace it with appropriate prefix #
prefix="C:/cygwin/";

#check for the partterns starting with "/" #
echo $var | grep "^/*$"
if [[ "$?" -eq "0" ]] ;then
  # check again whether parttern starts with /cygdrive/[a-z]/ parttern #
  if [[ $file == /cygdrive/[a-z]/* ]] ; then 
    file=${file#/cygdrive/[a-z]/};
    file="C:/"$file;
  else
    file="$prefix""$file";  
  fi 
fi


#check for the appropriate file permissions #
# :TODO: 


echo $file
exec "/cygdrive/c/Program Files (x86)/Programmer's Notepad/pn.exe"  $file 
Run Code Online (Sandbox Code Playgroud)

正如我在我的程序中,它在 cygwin 和 windows 之间转换路径名并加载 pn.exe [windows 中的程序员记事本]。所以我的问题是,

  1. "[[" 或 'test' 运算符有内置的正则表达式。(以及我在上面的程序中使用它们)。但如果我改变,为什么他们不在这里工作,

    echo $var | grep "^/*$"
    if [[ "$?" -eq "0" ]] ;then
    
    Run Code Online (Sandbox Code Playgroud)

    对此,

    if [[ "$file" == ^/*$ ]] ;then
    
    Run Code Online (Sandbox Code Playgroud)

    这是什么原因?有什么解决方法吗?我已经尝试过第二种方法,[[ "$file" == ^/*$ ]]但是没有用。然后,简单的谷歌搜索给我带来了这里:http : //unix.com/shell-programming

  2. 如何查找有关 [[ 运算符或 'test' 命令的所有文档?我用过 man test但是 :(。如果有,哪个文件指定了它对正则表达式使用的限制。

per*_*eal 5

首先,grep "^/*$"将只匹配只包含斜杠的路径,如“/”、“///”、“////”。您可以使用grep "^/"以匹配以斜杠开头的路径。如果要使用 bash 正则表达式:

var="/some"
#echo $var | grep "^/"
if [[ "$var" =~ ^/ ]] ;then
  echo "yes"
fi
Run Code Online (Sandbox Code Playgroud)