bash 如何将命令行参数放入shell脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4181999/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:55:00  来源:igfitidea点击:

How to put command line parameter to shell script

bashshell

提问by Learner_51

I have a executable shell script name project2. Following is one of the instruction my teacher gave me on the project.

我有一个名为 project2 的可执行 shell 脚本。以下是我的老师在该项目上给我的指导之一。

This script must accept at least one command line parameter: the directory where its output is to be placed. If that directory is not given on the command line, the script should use a reasonable default directory.

该脚本必须至少接受一个命令行参数:放置其输出的目录。如果命令行中未给出该目录,则脚本应使用合理的默认目录。

Can you please tell me how can I make my script accept a command line. I haven't done anything like that before. Any help would be greatly appreciated. Thanks a lot.

你能告诉我如何让我的脚本接受命令行。我以前没有做过这样的事情。任何帮助将不胜感激。非常感谢。

回答by paxdiablo

For bash, command line parameters are stored in $1, $2, and so on, while $#will give you the count. In addition, shiftcan be used to shift them all "left" by one position and drop the count.

对于bash,命令行参数存储在$1$2等中,而$#将为您提供计数。此外,shift可用于将它们全部“向左”移动一个位置并减少计数。

The following script is a good starting point for understanding how the parameters work:

以下脚本是了解参数工作原理的良好起点:

echo $#
while [[ $# -gt 0 ]] ; do
    echo ""
    shift
done

When you run it with:

当你运行它时:

./myprog.sh hello there my name is "pax     diablo"

the output is:

输出是:

6
hello
there
my
name
is
pax     diablo

The basic idea of your assignment is:

你的任务的基本思想是:

  • check the parameter count to see if it's zero.
  • if it is zero, set a variable to some useful default.
  • if it isn't zero, set that variable based on the first parameter.
  • do whatever you have to do with that variable.
  • 检查参数计数以查看它是否为零。
  • 如果为零,请将变量设置为一些有用的默认值。
  • 如果它不为零,则根据第一个参数设置该变量。
  • 对那个变量做任何你必须做的事情。

回答by sourcerebels

Take a look at this sectionof Advanced Bash Scripting guide.

看看这部分高级Bash脚本编程指南

I recommend you to read whole guide.

我建议您阅读整个指南。