shell $相关总结

1 $0, $1, $2,…, $n

  • $0:这个特殊一点表示命令本身;
  • $1: 表示第一个参数;
  • $2:表示第二个参数;
  • $n:表示第n个参数;
[root@localhost shell]# cat script.sh 
echo $0
echo $1
echo $2
[root@localhost shell]# ./script.sh Hello World
./script.sh
Hello
World

注意: 由于历史原因, $n只能针对10以内的数字,大于等于10需要用括号将数值包括起来

[jiangjian@localhost shell]$ cat echoArguments.sh 
#! /bin/bash
echo $1
echo $9
echo $10
echo ${10}
[jiangjian@localhost shell]$ ./echoArguments.sh 1 2 3 4 5 6 7 8 9 a b
1
9
10
a
[jiangjian@localhost shell]$ 

2 $#

$#:表示实际的参数个数;

[root@localhost shell]# cat arguments-length.sh 
echo "length is " $#
[root@localhost shell]# ./arguments-length.sh 1 2 3 4 5 6
length is  6

3 $$

$$:表示当前进程的pid;

[root@localhost shell]# cat output-pid.sh 
echo "my pid is " $$
[root@localhost shell]# ./output-pid.sh 
my pid is  47282
[root@localhost shell]# echo $$
46946
[root@localhost shell]# 

4 $?

$?:表示上一个命令执行的退出状态

[root@localhost shell]# cat error.sh 
exit 66 
[root@localhost shell]# ./error.sh 
[root@localhost shell]# echo $?
66
[root@localhost shell]# 

5 $!

$!:表示最近一个后台执行程序的pid;

[root@localhost shell]# sleep 60 &
[1] 47395
[root@localhost shell]# sleep 70 &
[2] 47396
[root@localhost shell]# echo $!
47396
[root@localhost shell]# 

6 $* 和 $@的区别

$*: Stores all the arguments that were entered on the
command line ($1 $2 …).

"$@": Stores all the arguments that were entered
on the command line, individually quoted ("$1" “$2” …).

[root@localhost shell]# cat arguments.sh 
#!/bin/bash

echo "Using \"\$*\":"
for a in "$*"; do
    echo $a;
done

echo -e "\nUsing \$*:"
for a in $*; do
    echo $a;
done

echo -e "\nUsing \"\$@\":"
for a in "$@"; do
    echo $a;
done

echo -e "\nUsing \$@:"
for a in $@; do
    echo $a;
done  
[root@localhost shell]# ./arguments.sh one two "three four"
Using "$*":
one two three four

Using $*:
one
two
three
four

Using "$@":
one
two
three four

Using $@:
one
two
three
four
[root@localhost shell]# 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值