Max*_*nko 5 scripts environment-variables
我想在 case 语句中使用变量作为条件。类似于:
#!/bin/sh
ALLOWED_SERVICES=tomcat6|james;
case $1 in
$ALLOWED_SERVICES )
service $1 restart
;;
* )
echo "Unsupported argument"
;;
esac
Run Code Online (Sandbox Code Playgroud)
这不起作用。当脚本以tomcat6参数为 exapmle启动时,它会输出“不支持的参数”消息。但是当 case 条件被硬编码时,它可以正常工作:
case $1 in
tomcat6|james )
service $1 restart
;;
* )
echo "Unsupported argument"
;;
esac
Run Code Online (Sandbox Code Playgroud)
在这种情况下可以使用变量吗?
问题是变量扩展和模式扩展都需要在匹配之前完成,而这在这里不起作用。如果您有可用的最新版本,bash您可以使用正则表达式匹配:
#!/bin/bash
ALLOWED_SERVICES="tomcat6|james"
if [[ $ALLOWED_SERVICES =~ $1 ]]; then
service $1 restart
else
echo "Unsupported argument"
fi
Run Code Online (Sandbox Code Playgroud)
添加shopt -s nocasematch在 之前,if使匹配不区分大小写。