如何在 bash 脚本中传递两个参数或参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25324162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass two parameters or arguments in bash scripting
提问by user1983063
I am new to bash scripting and I need your support to solve this problem. I have a bash script "start.sh". I want to write a script with two arguments so that I could run the script in the following way
我是 bash 脚本的新手,我需要您的支持来解决这个问题。我有一个 bash 脚本“start.sh”。我想编写一个带有两个参数的脚本,以便我可以按以下方式运行脚本
./start.sh -dayoffset 1 -processMode true
./start.sh -dayoffset 1 -processMode true
dayoffset and processMode are the two parameters that I have to script.
dayoffset 和 processMode 是我必须编写脚本的两个参数。
dayoffset = 1 is the reporting date (today) processMode = true or false
dayoffset = 1 是报告日期(今天) processMode = true 或 false
回答by konsolebox
As a start you can do this:
首先,您可以这样做:
#!/bin/bash
dayoffset=
processMode=
echo "Do something with $dayoffset and $processMode."
Usage:
用法:
./start.sh 1 true
Another:
其他:
#!/bin/bash
while [[ $# -gt 0 ]]; do
case "" in
-dayoffset)
day_offset=
shift
;;
-processMode)
if [[ != true && != false ]]; then
echo "Option argument to '-processMode' can only be 'true' or 'false'."
exit 1
fi
process_mode=
shift
;;
*)
echo "Invalid argument: "
exit 1
esac
shift
done
echo "Do something with $day_offset and $process_mode."
Usage:
用法:
./start.sh -dayoffset 1 -processMode true
Example argument parsing with day offset:
使用天偏移量解析示例参数:
#!/bin/bash
dayoffset=
date -d "now + $dayoffset days"
Test:
测试:
$ bash script.sh 0
Fri Aug 15 09:44:42 UTC 2014
$ bash script.sh 5
Wed Aug 20 09:44:43 UTC 2014