Linux 创建256个做同样事情的函数-创建一个不区分大小写的函数-一个将所有参数传递给函数的线性函数?
我想创建256个做同样事情的函数 基本上我想要一个能够不区分大小写地调用的函数 示例:我希望Linux 创建256个做同样事情的函数-创建一个不区分大小写的函数-一个将所有参数传递给函数的线性函数?,linux,macos,bash,function,terminal,osx,Linux,Macos,Bash,Function,Terminal,Osx,我想创建256个做同样事情的函数 基本上我想要一个能够不区分大小写地调用的函数 示例:我希望applepie()能够不敏感地调用case: applepie(){ for B in "$@"; do another_function_in_my_bash_profile $B blah blah # more stuff ... done } 最直接的方法是声明另外255个带有大写字母的函数: Applepie(){ for B in "$@"; do another_funct
applepie()
能够不敏感地调用case:
applepie(){
for B in "$@";
do
another_function_in_my_bash_profile $B
blah blah
# more stuff ...
done
}
最直接的方法是声明另外255个带有大写字母的函数:
Applepie(){
for B in "$@";
do
another_function_in_my_bash_profile $B
blah blah
# more stuff ...
done
}
及
一直到
APPLEPIE(){
for B in "$@";
do
another_function_in_my_bash_profile $B
blah blah
# more stuff ...
done
}
总共有256个(2的8次方)
有可能很快做到吗?还是有一种更“内置”的方法,比如
case-insensitive appelepie(){
for B in "$@";
do
another_function_in_my_bash_profile $B
blah blah
# more stuff ...
done
}
或者可以像这样做吗
case-insensitive APPLEPIE(){
command -pass_all_parameters applepie
}
它可以将所有参数传递给applepie,而不是在“$@”中为B使用for循环
?通过定义所有小写函数名并使用bash
的陷阱查找缺少的命令名,可以伪造不区分大小写的函数名(需要bash
4,您需要在OS X上安装):
因此,如果
apple
是一个函数,但您尝试将其称为apple
,则将使用该命令作为参数调用command\u not\u found\u handle
。第一行接受第一个参数(ApPlE
),小写。然后它尝试使用原始参数运行apple
。这是一个相当迟钝的答案,肯定不是一行,但下面是如何在中完成的,需要bc
和tr
的帮助(继续工作):
funcname=“applepie”
strlen=${funcname}
numcombos=$((2**strlen))
对于((i=1;i这里有另一种使用纯bash和递归函数的方法。当我看到递归函数时,我通常会跑一英里,但在这种情况下,它工作得非常好:
funcname="applepie"
function cr {
if [ "$1" ]; then
cr "${1:1:${#1}}" "${2:1:${#2}}" "${3}${1:0:1}"
cr "${1:1:${#1}}" "${2:1:${#2}}" "${3}${2:0:1}"
else
alias $3=$funcname
fi
}
cr $funcname $(tr '[a-z]' '[A-Z]' <<< $funcname) ""
funcname=“applepie”
功能铬{
如果[“$1”];则
cr“${1:1:${1}”${2:1:${2}”${3}${1:0:1}”
cr“${1:1:${1}}”${2:1:${2}”${3}${2:0:1}”
其他的
别名$3=$funcname
fi
}
cr$funcname$(tr'[a-z]'[a-z]'''+1表示非常聪明;但是在bash的较低版本中有没有办法做到这一点?小写很容易:cmd_name=$(tr'[a-z]'[a-z]'
command_not_found_handle () {
cmd_name=${1,,}
shift
$cmd_name "$@"
}
funcname="applepie"
strlen=${#funcname}
numcombos=$((2 ** strlen))
for ((i=1; i<numcombos; i++)); do
binstr=$(echo "obase=2; $i" | bc )
zlen=$((1+strlen-${#binstr}))
binstr=$(printf "%0${zlen}x" 0)${binstr}
binstr=${binstr:1:$strlen}
casename=""
for ((j=0; j<strlen; j++)); do
if [ ${binstr:$j:1} = 1 ]; then
casename=${casename}$(tr '[a-z]' '[A-Z]' <<< ${funcname:$j:1})
else
casename=${casename}${funcname:$j:1}
fi
done
alias ${casename}=${funcname}
done
funcname="applepie"
function cr {
if [ "$1" ]; then
cr "${1:1:${#1}}" "${2:1:${#2}}" "${3}${1:0:1}"
cr "${1:1:${#1}}" "${2:1:${#2}}" "${3}${2:0:1}"
else
alias $3=$funcname
fi
}
cr $funcname $(tr '[a-z]' '[A-Z]' <<< $funcname) ""