Shell script: 命令行参数

$0: 代表第一个参数,通常是脚本本身的名字
$1: 代表第二个参数
...
以此类推

例如:

#!/bin/bash

echo "\$0="$0
echo "\$1="$1
echo "\$2="$2

运行结果:

$ ./a.sh a b
$0=./a.sh
$1=a
$2=b

$@表示从第一到第n个参数,例如:

#!/usr/bin/bash

for arg in $@
do
    echo $arg
done

运行结果:

$ ./a.sh a b c
a
b
c

还有,当入参不存在的时候,可以有缺省值,例如:

#!/usr/bin/bash
para1=${1:-xxx}
echo $para1

运行结果:

$ ./c.sh abc
abc
$ ./c.sh 
xxx

更多内容,定义这里,感兴趣的自己看吧:
https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html

${parameter:-[word]}
Use Default Values. If parameter is unset or null, the expansion of word (or an empty string if word is omitted) shall be substituted; otherwise, the value of parameter shall be substituted.
${parameter:=[word]}
Assign Default Values. If parameter is unset or null, the expansion of word (or an empty string if word is omitted) shall be assigned to parameter. In all cases, the final value of parameter shall be substituted. Only variables, not positional parameters or special parameters, can be assigned in this way.
${parameter:?[word]}
Indicate Error if Null or Unset. If parameter is unset or null, the expansion of word (or a message indicating it is unset if word is omitted) shall be written to standard error and the shell exits with a non-zero exit status. Otherwise, the value of parameter shall be substituted. An interactive shell need not exit.
${parameter:+[word]}
Use Alternative Value. If parameter is unset or null, null shall be substituted; otherwise, the expansion of word (or an empty string if word is omitted) shall be substituted.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,796评论 19 139
  • 1.创建文件夹 !/bin/sh mkdir -m 777 "%%1" 2.创建文件 !/bin/sh touch...
    BigJeffWang阅读 13,469评论 3 53
  • 一,shell题记 不懂shell的程序员不是好程序员,学习shell是为了自动化,使用自动化可以非常有效的提高工...
    架构师小秘圈阅读 12,775评论 3 70
  • 与其抱怨生活糟糕,为什么不低头审视自己。人的内在变了,外在才会跟着变化,因为新的你才配得上新的生活。绝大多数人都在...
    e655d1e64997阅读 1,690评论 0 1
  • 咻! 天空之上,一道流光以一种惊人的速度掠过,隐约仿佛有着龙吟传荡开来,那是一道虚幻的龙影,龙影驮负着一道人影,自...
    混沌天书阅读 1,807评论 0 0