2013-08-21 60 views
1

我有一个程序,将采取用户输入字符串,并相应地创建输出文件,例如,“./bashexample2 J40087”这将创建文件夹中的所有文件的输出文件包含字符串J40087。一个问题是,如果用户没有在输入字符串中输入任何内容,它将为包含文件夹内的每个文件生成输出文件。有没有办法阻止用户在输入字符串中输入任何内容?或者可能吐出某种警告,说“请输入一个输入字符串”。如何防止用户输入任何东西在bash脚本

#Please follow the following example as input: xl-irv-05{kmoslehp}312: ./bashexample2 J40087 

#!/bin/bash 

directory=$(cd `dirname .` && pwd) ##declaring current path 
tag=$1 ##declaring argument which is the user input string 

echo find: $tag on $directory ##output input string in current directory. 

find $directory . -maxdepth 0 -type f -exec grep -sl "$tag" {} \; ##this finds the string the user requested 
for files in "$directory"/*"$tag"* ##for all the files with input string name... 
do 
    if [[ $files == *.std ]]; then ##if files have .std extensions convert them to .sum files... 
      /projects/OPSLIB/BCMTOOLS/sumfmt_linux < "$files" > "${files}.sum" 
    fi 

    if [[ $files == *.txt ]]; then ## if files have .txt extensions grep all fails and convert them.. 
     egrep "device|Device|\(F\)" "$files" > "${files}.fail" 
     fi 
     echo $files ##print all files that we found 
done 
+0

可能重复的[bash shell脚本检查输入参数](http://stackoverflow.com/questions/6482377/bash-shell-script-check-input-argument) – superEb

回答

3

我会做这样的事情:

tag=$1 

if [ -z "$tag" ]; then 
    echo "Please supply a string" 
    exit 1 
fi 
+0

嗨,你能告诉我什么-z命令可以吗? – kkmoslehpour

+0

如果字符串的长度为零,则返回true –

0

您可以使用$#知道有多少个参数作为参数已经过去了,然后询问是否有至少一个参数。

例如

if [ $# -gt 0 ]; then 
    ... your logic here ... 

作为一个说明分开,你可以通过阅读使用$ 1,对于第二个$ 2,依此类推脚本中的第一个参数。

希望有所帮助。