linux - 如何在 bash 脚本中传递两个参数或参数

标签 linux bash shell unix

<分区>

我是 bash 脚本的新手,我需要您的支持来解决这个问题。我有一个 bash 脚本“start.sh”。我想编写一个带有两个参数的脚本,以便我可以按以下方式运行脚本

./start.sh -dayoffset 1 -processMode true

dayoffset 和 processMode 是我必须编写脚本的两个参数。

dayoffset = 1 是报告日期(今天) processMode = true 或 false

最佳答案

作为开始,您可以这样做:

#!/bin/bash
dayoffset=$1
processMode=$2
echo "Do something with $dayoffset and $processMode."

用法:

./start.sh 1 true

另一个:

#!/bin/bash

while [[ $# -gt 0 ]]; do
    case "$1" in
    -dayoffset)
        day_offset=$2
        shift
        ;;
    -processMode)
        if [[ $2 != true && $2 != false ]]; then
            echo "Option argument to '-processMode' can only be 'true' or 'false'."
            exit 1
        fi
        process_mode=$2
        shift
        ;;
    *)
        echo "Invalid argument: $1"
        exit 1
    esac
    shift
done

echo "Do something with $day_offset and $process_mode."

用法:

./start.sh -dayoffset 1 -processMode true

使用日期偏移量解析的示例参数:

#!/bin/bash 
dayoffset=$1
date -d "now + $dayoffset days"

测试:

$ bash script.sh 0
Fri Aug 15 09:44:42 UTC 2014
$ bash script.sh 5
Wed Aug 20 09:44:43 UTC 2014

关于linux - 如何在 bash 脚本中传递两个参数或参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25324162/

相关文章:

java - Unix Daemon 是否应该有一个 main

bash 如何有选择地删除字符串中的空格

linux - 检测文件何时在 bash 中打开

bash - 语法错误 : Bad for loop variable

linux - Windows 上 ubuntu 服务器和 ubuntu 客户端的不同行为

bash - 如何解决 shell 脚本 : "read: Illegal option -t"? 中的此错误

python - RTSP 流和 OpenCV (Python)

python - 从行中搜索数字并放在特定句子中

linux - 了解 Unix 中的 I/O 重定向

linux - Linux 上的 NASM : Using sys_read adds extra line at the end