I want to add a flag to alias, in my case I want do it for bat. e.g.
mybat -a = 'bat --paging=always [file e.g .zshrc]'
mybat -n = 'bat --paging=never [file e.g .zshrc] '
I also wrote and tested the following code, but it did not work:
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
}
Anyone have an idea?
CodePudding user response:
I don't have bat
so I substituted cat
and added a few cat
-specific flags:
$ 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
One function approach where we simply replace the first short option with its corresponding long option:
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
}
NOTE: remove the set -xv/ xv
once satisfied the function is working as planned
Test file:
$ cat words.dat
I am a man post-tab # <tab> between "man" and "post-tab"
I am not a man I
am a man
Taking the function for a test drive:
$ 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
CodePudding user response:
Sticking with the alias approach, define 2x different aliases, eg:
mybata='bat --paging=always'
mybatn='bat --paging=never'
NOTE: pick aliases that are short-to-type and easy-to-remmber, eg, mybata
vs mybat_a
vs mybat-a
vs mba
...