首页 > 解决方案 > .sh 文件无法回显在 bash 中定义的变量

问题描述

我正在尝试使用在 shell 中定义的 .sh 和变量生成 HTML 文件

     [root@ip-xxx-xx-x-xxx Reporting]: IMAGE_TAG=xyzabc

.sh 文件代码

      #!/bin/bash
      echo "<!DOCTYPE html>" > fargateproductiondeploy.html
      echo "<html> <body>" >> fargateproductiondeploy.html
     echo "<h2>Following Docker container 
     will be deployed  will be Deployed in production up on Approval </h2> 
     <ol>" >> fargateproductiondeploy.html
     echo "<li>$IMAGE_TAG </li>" >> fargateproductiondeploy.html

从 HTML 文件中运行 ./generatehtml.sh 后

            Following Docker container will be deployed will be Deployed in 
            production upon Approval 
            1.

标签: bashshellvariablesscripting

解决方案


您需要先导出变量

$ export IMAGE_TAG=xyzabc
$ ./generatehtml.sh

或源文件

$ IMAGE_TAG=xyzabc
$ . ./generatehtml.sh

最好将值作为参数传递。

#!/bin/bash
image_tag=$1

echo "<!DOCTYPE html>" > fargateproductiondeploy.html
echo "<html> <body>" >> fargateproductiondeploy.html
echo "<h2>Following Docker container will be deployed  will be Deployed in production up on Approval </h2> <ol>" >> fargateproductiondeploy.html
echo "<li>$image_tag </li>" >> fargateproductiondeploy.html

其次是

$ ./generatehtml.sh xyzabc

推荐阅读