TCSH脚本 - 如何通过foreach循环解析无效参数?

时间:2015-10-11 20:13:32

标签: shell csh tcsh

我想在我的foreach中解析,如果有人通过无效论证,意思是 - (此处的任何内容,除了字母&#39; h&#39;或&#39; q&#39;)< / p>

我的代码:

#!/bin/tcsh
foreach i ( $* )
  if($i == "--help" || $i == "-h" )then 
    echo 'Script shows name, surname, login of the invoker. Possible parameters: \n -h/--help - help \n -q/--quit - quit'
    exit 0;
  endif
end

foreach i ( $* )
  if($i == "--quit" || $i == "-q" )then 
    exit 0;
  endif
end
#Here, i thought it will work, but not  
foreach i ( $* )
  if($i == "-*")then
    echo " invalid argument"  
    exit 0;
  endif
end


echo $USER
getent passwd $USER | cut -d: -f5 | cut -d, -f1
exit 0;

2 个答案:

答案 0 :(得分:0)

尝试

if($i =~ [-]*)then

答案 1 :(得分:0)

当变量包含 - 时,您需要小心不引用变量,因此请用双引号括住所有$i,如下所示:"$i"

man tcsh为您提供有关glob功能的信息,搜索&#39;&#39; glob-patterns&#39;&#39;和&#39;&#39;文件名替换&#39;&#39;。

适合我的固定脚本是:

#!/bin/tcsh -f
foreach i ( $* )
  if ( "$i" == "--help" || "$i" == "-h" ) then
    echo 'Script shows name, surname, login of the invoker. Possible parameters:'
    echo '  -h/--help - help'
    echo '  -q/--quit - quit'
    exit 1
  endif
  if ( "$i" == "--quit" || "$i" == "-q" ) then
    exit 0
  endif
  if ( "$i" =~ [-]* ) then
    echo " invalid argument: $i"
    exit 0
  endif
end