我有一个bash脚本,它使用getopts
解析命令行参数。其中一个参数-l <name>
被定向到一个确定某些设置的if
语句。是否有可能在命令行中自动完成输入<name>
参数的工作?
下面是我脚本的命令行解析部分(getopts
):
while getopts 'l:r:m:?h' c
do
case $c in
l)
library=$OPTARG
;;
r)
rename_config=$OPTARG
;;
m)
align_mm=$OPTARG
;;
h|?) usage
;;
esac
done
库选项(-l
)指向脚本的这一部分:
if [ $library = "bassik" ];
then
read_mod="clip"
clip_seq="GTTTAAGAGCTAAGCTGGAAACAGCATAGCAA"
echo "Bassik library selected"
elif [ $library = "moffat_tko1" ];
then
read_mod="trim"
sg_length=20
echo "Moffat TKO1 library selected"
elif [ $library = "sabatini" ];
then
read_mod="trim"
sg_length=20
echo "Sabatini library selected"
fi
应该自动完成的部分是"bassik", "moffat_tko1"one_answers"sabatini"参数。到目前为止,我已经尝试在./script.sh -l
之后击中<TAB>
,但这不起作用。我用谷歌搜索了一下,但找不到任何适合我的情况的东西(也不确定如何称呼它,对bash来说是新的)。
首先,我将您的脚本片段复制到一个名为auto.sh的文件中,并设置了执行权限:
#!/bin/bash
while getopts 'l:r:m:?h' c
do
case $c in
l)
library=$OPTARG
;;
r)
rename_config=$OPTARG
;;
m)
align_mm=$OPTARG
;;
h|?) usage
;;
esac
done
if [ $library = "bassik" ];
then
read_mod="clip"
clip_seq="GTTTAAGAGCTAAGCTGGAAACAGCATAGCAA"
echo "Bassik library selected"
elif [ $library = "moffat_tko1" ];
then
read_mod="trim"
sg_length=20
echo "Moffat TKO1 library selected"
elif [ $library = "sabatini" ];
then
read_mod="trim"
sg_length=20
echo "Sabatini library selected"
fi
然后,要为-l
选项设置自动完成,您可以从这些基本步骤开始(这可以在将来增强):
1。创建一个补全脚本(例如/auto-complete.sh),其中包含在补全请求时调用的libs函数(complete命令的-F
参数)。如果-l
选项是补全位置($3
参数)前面的单词,则该函数触发库名称的显示( comply 数组变量的内容):
function libs()
{
# $1 is the name of the command
# $2 is the word being completed
# $3 is the word preceding the word being completed
case $3 in
-l) COMPREPLY+=("bassi")
COMPREPLY+=("moffat_tko1")
COMPREPLY+=("sabatini");;
esac
}
complete -F libs auto.sh
2。在本地shell中获取脚本:
$ source ./auto-complete.sh
3。启动shell脚本,在-l
选项后面的空格后面键入两次TAB
key:
$ ./auto.sh -l <tab><tab>
bassik moffat_tko1 sabatini
$ ./auto.sh -l bassik
Bassik library selected
4。前面系统地列出了输入TAB
键时的所有选项。为了在输入首字母时更准确地完成,可以对补全脚本进行增强,使用compgen command:
function libs()
{
# $1 is the name of the command
# $2 is the word being completed
# $3 is the word preceding the word being completed
case $3 in
-l) COMPREPLY=($(compgen -W "bassik moffat_tko1 sabatini" "${COMP_WORDS[$COMP_CWORD]}"));;
esac
}
complete -F libs auto.sh