shell 参数

位置参数

所谓位置参数 (positional parameter) ,指的是 Shell 脚本的命令行参数 (argument) ;同时也表示在 Shell 函数内的函数参数。它们的名称是以单个的整数来命名。出于历史的原因,当这个整数大于 9 时,就应该以花括号( {} )括起来 :

echo first arg is $1
echo tenth arg is ${10}

特殊变量参数

$#

提供传递到 Shell 脚本或者函数的参数总数。

$*,$@

一次表示所有的命令行参数.这两个参数可用来把命令行参数传递给脚本或函数所执行的程序.

“$*”

将所有命令行参数视为单个字符串,等同于“$1 $2...”。$lFS 的第一个字符用来作为分隔字符,以分隔不同的值来建立字符串

“$@”

将所有的命令行参数视为单独的个体,也就是单独字符串,等同于"$1" "$2" ..这是将参数传递给其他程序的最佳方式,因为它会保留所有内嵌在每个参数里的任何空白

# 设置参数
qiweijie@qiweijie:~$ set -- hello "hi there " greetings
qiweijie@qiweijie:~$ echo $#
3
# 没有加引号的 $*和$@是一样的效果
qiweijie@qiweijie:~$ for i in $*
> do echo i is $i
> done
i is hello
i is hi
i is there
i is greetings
qiweijie@qiweijie:~$ for i in $@; do echo i is $i; done
i is hello
i is hi
i is there
i is greetings
# 加了引号的,两个就不一样了
qiweijie@qiweijie:~$ for i in "$*"; do echo i is $i; done
i is hello hi there greetings
qiweijie@qiweijie:~$ for i in "$@"; do echo i is $i; done
i is hello
i is hi there
i is greetings
qiweijie@qiweijie:~$ 
qiweijie@qiweijie:~$ shift
qiweijie@qiweijie:~$ echo $#
2
qiweijie@qiweijie:~$ shift 
qiweijie@qiweijie:~$ echo $#
1

p

原文地址:https://www.cnblogs.com/qwj-sysu/p/5007408.html