如果有人运行-9并且在标志之后没有为OPTARG放置任何东西,我想让ops默认为-8标志。或者我可以检查OPTARG是否为空并用基值替换空值。
ft1和ftx只是格式化函数。
当我运行我的goat -8
时,它打印出有问题的文件
当我运行goat -9 SEARCH STRING
时,它打印的文件只包含该搜索字符串的结果。
如果我运行goat -9
并且不放置搜索字符串它什么都不做因为OPTARG
是空白的所以grep没有什么可搜索的。
如果用户在-9
之后没有输入字符串,我希望能够将-8
更改为goat -9
。
function goat() {
local OPTIND
local OPTARG
if [ "$1" = "" ] ;
then ft1 ;
printf "
This command requires an OPTION. Refer to the help menu (-h) for assistance.
" | layoutcc
ft1 ;
fi
while getopts ":h89:" opt;
do case $opt in
8) for file in analysis/connection_history.txt ; do ftx $file | layoutcc ;
printf "%s" "$(<$file)"
echo ;
ft1 ;
done
;;
9) grep_expr=$OPTARG
for file in analysis/connection_history.txt ; do
ftx "$file" | layoutcc
grep "$grep_expr" $file | perl -ne 'print if /-201[8-9]/' |
perl -pe 's/......-2019/\e[1;32m$&\e[0m/g'
echo
ft1
done
;;
function ft1
{
printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' =
}
function ft2
{
ft1 ;
ft1
}
function ftx
{
ft1 ;
echo " File Name: $1 $(grep -h "Created on" *-Report.txt | head -n1)"
ft1
}
function fsx
{
ft1 ;
echo " File Name: $1"
ft1
}
我会从解析代码的选项中获取业务逻辑:
grep_expr=""
has_8=false
has_9=false
while getopts ":h89:" opt; do
case $opt in
h) do_some_h_thing ;;
8) has_8=true ;;
9) has_9=true; grep_expr=$OPTARG ;;
:) echo "Error: missing argument for option -$OPTARG" >&2; exit 1 ;;
*) echo "Error: unknown option -$OPTARG" >&2; exit 1 ;;
esac
done
shift $((OPTIND - 1))
if $has_8 || ($has_9 && [[ -z $grep_expr ]]); then
for file in analysis/connection_history.txt ; do
ftx $file | layoutcc
printf "%s" "$(<$file)" # why not `cat "$file"` ?
echo ; #
ft1 ;
done
elif $has_9; then
for file in analysis/connection_history.txt ; do
ftx "$file" | layoutcc
# following pipeline can be greatly simplified
grep "$grep_expr" $file |
perl -ne 'print if /-201[8-9]/' |
perl -pe 's/......-2019/\e[1;32m$&\e[0m/g'
echo
ft1
done
else
echo "Error: you must use one of '-8' or '-9 basic_regex'" >&2
exit 1
fi