shell shift用法

参数 描述
$0 命令本身
$1,$2… 第1个参数、第2个参数……
$# 参数的个数,不包括$0
$@ 以列表的形式返回参数列表,不包括$? 最后运行的命令结束代码

Example 1

shift_test.sh

1
2
3
4
5
6
7
cat shift_test.sh
#!/bin/bash
while [ $# != 0 ]
do
echo "prama is $1,prama size is $#"
shift
done

运行结果如下:

1
2
3
4
# ./shift_test.sh a b c
prama is a,prama size is 3
prama is b,prama size is 2
prama is c,prama size is 1

Example 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 # cat img_downloader.sh
#!/bin/bash

if [ $# -ne 3 ];
then
echo "Usage: $0 URL -d DIRECTORY"
exit 1
fi

while [ $# -gt 0 ]
do
case $1 in
-d) shift; directory=$1; shift ;;
*) url=$1; shift;;
esac
done

echo "directory is :$directory"
echo "url is :$url"

运行结果如下:

1
2
3
4
5
6
 # ./img_downloader.sh -d images baidu.com
directory is :images
url is :baidu.com
# ./img_downloader.sh baidu.com -d images
directory is :images
url is :baidu.com

采用这种方法解析命令行参数的好处在于可以将 -d 置于命令行中的任意位置

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2019-2024 John Doe
  • Visitors: | Views:

请我喝杯咖啡吧~