在外壳的命令行参数传递 [英] Pass parameters from the command line in shell
问题描述
DATE1=`perl -e 'use POSIX qw(strftime); print strftime "%Y-%m-%d",localtime(time()- 3600*72);'`
DATE2=`perl -e 'use POSIX qw(strftime); print strftime "%Y%m%d",localtime(time()- 3600*72);'`
DATE3=`perl -e 'use POSIX qw(strftime); print strftime "%Y%m%d",localtime(time()- 3600*48);'`
DATE4=`perl -e 'use POSIX qw(strftime); print strftime "%Y/%m/%d",localtime(time()- 3600*48);'`
下面是我的shell脚本(test1.sh),其中我需要打印的四个日期和所有四个日期应该从上面。这意味着我需要这些四个日期以上通过从命令提示符只对下面的shell脚本。
Below is my shell script(test1.sh), in which I need to print four dates and all those four dates should come from above. Meaning I need to pass above those four dates from the command prompt only to the below shell script.
#!/bin/bash
echo Date1
echo Date2
echo Date3
echo Date4
所以,当我运行shell脚本喜欢这个 - 它应该从以上四个日期获取日期1,日期2,DATE3,Date4?
So when I am running the shell script like this- it should get Date1, Date2, Date3, Date4 from the above four dates?
sh -x test1.sh Date1 Date2 Date3 Date4
是否有可能在shell脚本来完成?
Is it possible to do in shell script?
推荐答案
如果您在shell执行你的第一个code块,那么你就已经定义了4个变量与命令的输出。访问任何这些变量,你必须prePEND一个 $
来的变量名 - 例如, $ DATE1
。
If you execute your first code-block in a shell, then you'll have defined 4 variables with the output of those commands. To access any of those variables, you have to prepend a $
to the variable name - say, $DATE1
.
因此,对于这些参数运行脚本,你应该运行:
So, for running your script with those parameters, you should run:
bash -x test1.sh $DATE1 $DATE2 $DATE3 $DATE4
,请注意 $
和案例敏感。
最后,在你的脚本,参数在变量的家庭被调用的参数的顺序号收到。所以,你的第一个参数是由 $ 1
检索,第二个由 $ 2
,等等。
Finally, in your script, arguments are received in a family of variables that are called with the number of order of the parameter. So, your first parameter is retrieved by $1
, the second by $2
, and so on.
所以,你的脚本结束是:
So, your script ends up being:
#!/bin/bash
echo $1
echo $2
echo $3
echo $4
手表也正在定义一个她邦告诉脚本是由庆典
PTED间$ P $,但你的previous调用使用 SH
。他们有很多兼容性的,但他们是不一样的。
Watch also that you are defining a she-bang that tells the script to be interpreted by bash
, but your previous invocation was using sh
. They have lots of compatibilities, but they are not the same.
这篇关于在外壳的命令行参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!