I have a program that will take user input string and create output files accordingly, for example, "./bashexample2 J40087" this will create output files for all the files in the folder that contain the string J40087. One problem is that if the user does not input anything in the input string it will generate output files for every file inside the containing folder. Is there a way to prevent user to input nothing in the input string? Or maybe spit out some sort of warning saying " please input an input string".
我有一个程序,它将接受用户输入字符串并相应地创建输出文件,例如,”。这将为包含字符串J40087的文件夹中的所有文件创建输出文件。一个问题是,如果用户没有在输入字符串中输入任何内容,它将为包含该文件夹的每个文件生成输出文件。是否有一种方法可以防止用户在输入字符串中不输入任何内容?或者可能会说一些警告说“请输入一个输入字符串”。
#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
2 个解决方案
#1
3
I would do something like this:
我会这样做:
tag=$1
if [ -z "$tag" ]; then
echo "Please supply a string"
exit 1
fi
#2
0
You can use $# to know how many arguments has been passed as parameters and then ask if there is at least one argument.
您可以使用$#来了解作为参数传递了多少个参数,然后询问是否至少有一个参数。
For example
例如
if [ $# -gt 0 ]; then
... your logic here ...
As a note apart, you can read the first parameter passed to your script using $1, and $2 for the second one, and so on.
另外,您可以使用$1读取传递给脚本的第一个参数,第二个参数$2,以此类推。
Hope that helps.
希望有帮助。
#1
3
I would do something like this:
我会这样做:
tag=$1
if [ -z "$tag" ]; then
echo "Please supply a string"
exit 1
fi
#2
0
You can use $# to know how many arguments has been passed as parameters and then ask if there is at least one argument.
您可以使用$#来了解作为参数传递了多少个参数,然后询问是否至少有一个参数。
For example
例如
if [ $# -gt 0 ]; then
... your logic here ...
As a note apart, you can read the first parameter passed to your script using $1, and $2 for the second one, and so on.
另外,您可以使用$1读取传递给脚本的第一个参数,第二个参数$2,以此类推。
Hope that helps.
希望有帮助。