问题描述
我当前的 Bash 脚本如下所示。到目前为止它正在工作,但我不知道如何使它这样两个选项 -f 和 -o 一起工作:
- -o FILE 选项显示最相关的信息 在作为参数传递的文件中(如果文件不存在,则必须显示错误消息)
- 选项 -f KEYWORD 显示包含 KEYWORD 的行 从一个文件。此选项必须与 -o 选项一起使用
感谢您的任何意见
#!/bin/bash
function s_func()
{
filename="$1";
echo "when you're done saving information please write 'exit'"
script $filename.txt
}
function o_func()
{
filename="$1"
dest='/home/eya/'
if [ -f "$filename".txt ]; then
cat $filename.txt
else echo "file does not exist"
fi
}
function f_func()
{
keyword="$1"
filename="$2"
grep $keyword $filename.txt
}
while getopts ":s:o:f:" opt; do
case $opt in
s) s_func "$OPTARG";;
o) o_func "$OPTARG";;
f) f_func "$OPTARG";;
\?)echo "wrong option";exit 1;;
esac
done
shift $((OPTIND -1))
解决方法
试试这个:在处理命令行选项时,只收集变量。 仅在解析选项之后使用这些变量。
declare f_arg o_arg s_arg
while getopts ":s:o:f:" opt; do
case $opt in
s) s_arg=$OPTARG ;;
o) o_arg=$OPTARG ;;
f) f_arg=$OPTARG ;;
esac
done
shift $((OPTIND -1))
if [[ -z $o_arg ]] || [[ -z $f_arg ]] || [[ -z $s_arg ]]; then
echo "ERROR: Options -s,-o and -f are required." >&2
exit 1
fi
# Now you can do stuff in a specific order.
o_func "$o_arg"
f_func "$f_arg"
s_func "$s_arg"