shell 脚本错误:语法错误:“(”意外

Bob*_*bby 4 shell bash shell-script syntax

我已经检查了有关此错误的上一篇文章。仍然没有得到解决方案的工作。这是我的 bash 脚本。有人可以帮我解决这个问题吗?我已经使用https://www.shellcheck.net/查看任何错误。我没有找到。

错误:

Dockerfunctiontest.sh: 2: Dockerfunctiontest.sh: Syntax error: "(" unexpected
Run Code Online (Sandbox Code Playgroud)

脚本:

#!/bin/bash
function BuildSimpleContainer ()
{
docker search mariadb
docker pull mariadb:latest
docker run --name mariadbtestfour -e MYSQL_ROOT_PASSWORD=mypass -d mariadb --log-bin --binlog-format=MIXED
docker exec -it mariadbtest bash
apt-get -qq update
apt-get -qq -y install curl
apt-get -qq -y install wget
apt-get update
apt-get install apt-transport-https
apt-get update
cd /home
mkdir mdsd
cd mdsd/
wget '<blob url to pfx file>'
echo "certififcate Downloaded"
wget '<blob url file1>'
echo "file1 Downloaded"
wget 'blob url file2'
echo "file2 Downloaded"
}   
BuildSimpleContainer
Run Code Online (Sandbox Code Playgroud)

小智 8

我的猜测是您不会将此脚本作为 Bash 脚本运行,而是使用其他一些不接受此语法的 shell。例如。sh.

正如您在 Shellcheck 中看到的,并且正如man我的 Debian 上的Bash 所确认的那样,此语法是正确的:

name () compound-command [redirection]
function name [()] compound-command [redirection]
Run Code Online (Sandbox Code Playgroud)

您正在使用上面两个中的第二个,并且您compound-command{...}大括号的内容。就目前而言,这很好man bash。但是,有人反对这种结构,正如约翰·穆恩 (John Moon) 评论中另一个答案下方的链接所示。并再次在该答案中指向 Greg's Wiki 的链接中。

回到您的问题,考虑到脚本的名称,即Dockerfunctiontest.sh,我可能认为您看不到sh和之间的太大区别bash。可能您使用以下命令运行脚本:

sh Dockerfunctiontest.sh
Run Code Online (Sandbox Code Playgroud)

虽然使用以下任一方式运行它是合理的:

bash Dockerfunctiontest.sh
Run Code Online (Sandbox Code Playgroud)

或者

./Dockerfunctiontest.sh
Run Code Online (Sandbox Code Playgroud)

最后一个根据脚本中的第一行选择解释器,即:

#!/bin/bash
Run Code Online (Sandbox Code Playgroud)

虽然脚本中命名的解释器是 Bash,但为什么不以正确的方式命名文件呢?

Dockerfunctiontest.bash
Run Code Online (Sandbox Code Playgroud)

以后少迷茫。