shell函数返回值与字典shell的函数只能返回整数值,如果想让函数返回字符串可以在函数调⽤处为变量赋值。
# 定义函数
function test() {
name=$1
echo "123213"
}
# 调⽤函数,执⾏结果赋值给变量ret
ret=$(test "lishichao")
echo $ret
# 执⾏结果
[root@dev-test shell]# sh test.sh
123213
最近在写⼀键安装脚本,⼀个⼀个判断输⼊参数太⿇烦,所以使⽤shell字典匹配对应函数。function main(){
if [[ $USER != "root" ]]
then
echo "Please use root account"
exit
fi
if [[ -z $VAR ]]
then
echo "please input your action:pypy,nginx,redis,mysql,hall0,hall37"
exit
fi
case $VAR in
"pypy")
install_pypy5
;;
"nginx")
nginx
;;
"redis")
install_redis
;;
"mysql")
install_mysql
;;
"hall0")
hall0
;;
"hall37")shell脚本返回执行结果
hall37
;;
*)
echo "please input your action:pypy,nginx,redis,mysql,hall0,hall37"
;
;
esac
}
main
使⽤case判断输⼊参数
function install_php() {
echo "安装php7"
exit 0
}
function install_filebeat() {
echo "安装filebeat"
exit 0
}
function install_rabbitmq() {
echo "安装rabbitmq"
exit 0
}
function install_logstash() {
echo "安装logstash"
exit 0
}
declare -A dic
dic=([php]=install_php [logstash]=install_logstash [filebeat]=install_filebeat)
VAR=$1
for key in $(echo ${!dic[*]})
do
if [[ $VAR == $key ]];then
${dic[$VAR]}
echo "$key"
fi
done
echo "$(pwd)/$0 {pypy | nginx | redis | mysql | hall0 | hall37 | rabbitmq | logstash | filebeat}"
执⾏结果:
[root@dev-test shell]# sh test.sh
/opt/shell/test.sh {pypy | nginx | redis | mysql | hall0 | hall37 | rabbitmq | logstash | filebeat} [root@dev-test shell]# sh test.sh logstash
安装logstash
[root@dev-test shell]# sh test.sh filebeat
安装filebeat
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论