我想为别名添加一个标志,在我的情况下,我想为bat添加一个标志。例如
mybat -a = 'bat --paging=always [file e.g .zshrc]'
mybat -n = 'bat --paging=never [file e.g .zshrc] '
我还编写并测试了以下代码,但它不起作用:
mybat() {
local OPTIND value
while getopts ":an" option; do
case $option in
a) value=never ;;
n) value=always ;;
?) echo "invalid option: $OPTARG"; return 1 ;;
esac
done
bat --paging=$value
}
有人知道吗?
我没有bat
,所以我替换了cat
并添加了一些cat
特定的标志:
$ man cat
-A, --show-all equivalent to -vET -b, --number-nonblank number nonempty output lines, overrides -n -E, --show-ends display $ at end of each line -n, --number number all output lines
一种简单地将第一个短选项替换为对应的长选项的函数方法:
mycat() {
unset value
inputs="$@"
option="${inputs%% *}" # assumes only looking to parse first input arg
case $option in
-A) value='--show-all'; shift ;;
-b) value='--number-nonblank'; shift ;;
-E) value='--show-ends'; shift ;;
-n) value='--number'; shift ;;
esac
set -xv
cat ${value} "$@" # don't wrap ${value} in double quotes otherwise mycat() call with no flags will be invoked as "cat '' <filename>" and generate an error
set +xv
}
注意:一旦满足功能按计划工作,删除set -xv/+xv
测试文件:
$ cat words.dat
I am a man post-tab # <tab> between "man" and "post-tab"
I am not a man I
am a man
取函数进行试驾:
$ mycat -n words.dat
+ cat --number words.dat
1 I am a man post-tab
2 I am not a man I
3 am a man
$ mycat -A words.dat
+ cat --show-all words.dat
I am a man^Ipost-tab$ # ^I == <tab>
I am not a man I$
am a man$
$ mycat -b words.dat
+ cat --number-nonblank words.dat
1 I am a man post-tab
2 I am not a man I
3 am a man
$ mycat -E words.dat
+ cat --show-ends words.dat
I am a man post-tab$
I am not a man I$
am a man$
$ mycat -A -n words.dat # 2x options; only replace 1st option
+ cat --show-all -n words.dat
1 I am a man^Ipost-tab$
2 I am not a man I$
3 am a man$
$ mycat words.dat # no options
+ cat words.dat
I am a man post-tab
I am not a man I
am a man
坚持使用别名的方法,定义2个不同的别名,例如:
mybata='bat --paging=always'
mybatn='bat --paging=never'
注意:选择简短且易于记忆的别名,例如,mybata
vsmybat_a
vsmybat-a
vsmba
…