繁体   English   中英

如何让 shell 脚本在没有输入的情况下运行函数

[英]How do you get a shell script to run a function with no input

我有一个任务来编写一个 shell 脚本(除其他外)在没有任何参数的情况下执行时,脚本将执行以下步骤:

更新所有系统包 安装 Nginx 软件包 配置 nginx 在系统启动时自动启动。 将网站文档复制到网页文档根目录。 启动 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

将您的“case”代码包装在 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM