首页 > 解决方案 > 你如何获得一个shell脚本来运行一个没有输入的函数

问题描述

我有一个任务是编写一个 shell 脚本(除其他外),当不带任何参数执行时,该脚本将执行以下步骤:

更新所有系统包 安装 Nginx 软件包 配置 nginx 在系统启动时自动启动。将网站文档复制到 Web 文档根目录。启动 Nginx 服务。

我已经编写了脚本应该执行的任务,但我不知道如何构建脚本,以便它仅在没有任何参数的情况下运行这些任务。

每当我运行脚本 - 参数时,这些任务都会被执行。我已经将任务包装在一个函数中,但我不知道如何提示它只在没有参数的情况下运行:

#!/bin/bash
# assign variables
ACTION=${1}
Version=1.0.0

function default(){
sudo yum update -y
sudo yum install httpd -y
sudo yum install git -y
sudo amazon-linux-extras install nginx1.12 -y
sudo systemctl start nginx.service
sudo systemctl enable nginx.service
sudo aws s3 cp s3://index.html /usr/share/nginx/html/index.html
}


...

case "$ACTION" in
        -h|--help)
                display_help
                ;;
    -r|--remove)
        script_r_function
                ;;
        -v|--version)
                ;;
                show_version "Version"
                ;;
        default
        *)
        echo "Usage ${0} {-h|-r|-v}"
        exit 1
esac

标签: linuxshellunixamazon-ec2

解决方案


将您的“案例”代码包装在 if else 中:

#!/bin/bash
# assign variables
ACTION=${1}
if [ "$#" -eq 0 ]; then
    echo "no arguments"
else
case "$ACTION" in
        -h|--help)
                echo "help"
                ;;
        -r|--remove)
                echo "remove"
                ;;
        -v|--version)
                echo "version"
                ;;
        *)
        echo "wrong aruments"
        exit 1
esac
fi
  • 当我没有给出任何论点时:
./boo
no arguments
  • 当我给出错误的论点时:
 ./boo -wrong
wrong aruments
  • 当我给出有效的论点时(例如:版本):
./boo -v
version

推荐阅读