【问题标题】:How do you get a shell script to run a function with no input你如何获得一个shell脚本来运行一个没有输入的函数
【发布时间】:2021-01-15 16:04:13
【问题描述】:

我有一个任务是编写一个 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

【问题讨论】:

  • 以上帖子告诉您如何获取传递给脚本的参数数量。所以可以在该值为 0 时运行该函数。
  • @kaylum 也许我遗漏了一些东西,但我并没有试图找出参数的数量,而是在我的代码(默认)中运行该函数,该函数仅在没有任何运行时安装所需的包论据。
  • 这正是检查无参数会给你的。如果数字为 0,则运行函数,否则执行 case 语句。
  • "当没有任何参数运行时" == "参数数量为 0"。不知道为什么不清楚。如果您有办法获取调用脚本时使用的 args 数量,那么您可以确定是否有任何 args。

标签: linux shell unix amazon-ec2


【解决方案1】:

在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    • 2013-04-18
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 2022-07-14
    相关资源
    最近更新 更多