codecamp

4.2.2 接收用户的参数

但是,像上面这样的脚本程序只能执行一些预先定义好的功能,未免太过死板了。为了让Shell脚本程序更好地满足用户的一些实时需求,以便灵活完成工作,必须要让脚本程序能够像之前执行命令时那样,接收用户输入的参数。

其实,Linux系统中的Shell脚本语言早就考虑到了这些,已经内设了用于接收参数的变量,变量之间可以使用空格间隔。例如$0对应的是当前Shell脚本程序的名称,$#对应的是总共有几个参数,$*对应的是所有位置的参数值,$?对应的是显示上一次命令的执行返回值,而$1、$2、$3……则分别对应着第N个位置的参数值,如图4-15所示。

图4-15 Shell脚本程序中的参数位置变量

理论过后我们来练习一下。尝试编写一个脚本程序示例,通过引用上面的变量参数来看下真实效果:

    [root@linuxprobe ~]# vim example.sh
    #!/bin/bash
    echo "当前脚本名称为$0"
    echo "总共有$#个参数,分别是$*。"
    echo "第1个参数为$1,第5个为$5。"
    [root@linuxprobe ~]# sh example.sh one two three four five six
    当前脚本名称为example.sh
    总共有6个参数,分别是one two three four five six。
    第1个参数为one,第5个为five。

4.2.1 编写简单的脚本
4.2.3 判断用户的参数
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }