shift
命令的用法
shift
命令用于 左移脚本中的位置参数,即 $1
、$2
等。它会丢弃当前的 $1
,然后 $2
变成新的 $1
,$3
变成 $2
,以此类推。
语法
shift [n]
n
:表示左移的次数,默认为1
。- 每执行一次
shift
,位置参数都会整体向左移动。
示例 1:基本使用
#!/bin/bash
echo "Before shift:"
echo "Arg1: $1"
echo "Arg2: $2"
echo "Arg3: $3"
shift # 左移一次
echo "After shift:"
echo "Arg1: $1"
echo "Arg2: $2"
echo "Arg3: $3"
执行
$ ./script.sh A B C
Before shift:
Arg1: A
Arg2: B
Arg3: C
After shift:
Arg1: B
Arg2: C
Arg3:
shift
后,$1
变成B
,$2
变成C
,$3
变为空。
示例 2:循环处理参数
使用 shift
可以依次处理传入的所有参数:
#!/bin/bash
while [[ $# -gt 0 ]]; do
echo "Processing argument: $1"
shift # 移动到下一个参数
done
执行
$ ./script.sh apple banana cherry
Processing argument: apple
Processing argument: banana
Processing argument: cherry
shift
逐步移动参数,直到$#
变为0
(即没有参数)。
示例 3:shift n
(左移多个参数)
shift n
可以一次性跳过多个参数:
#!/bin/bash
echo "Before shift:"
echo "All args: $@"
shift 2 # 左移两次,跳过前两个参数
echo "After shift:"
echo "All args: $@"
执行
$ ./script.sh A B C D
Before shift:
All args: A B C D
After shift:
All args: C D
shift 2
使$1
直接变成C
,$2
变成D
。
示例 4:结合 getopts
使用
在 getopts
解析参数时,shift
可以跳过已经处理的选项:
#!/bin/bash
while getopts "a:b:" opt; do
case $opt in
a) echo "Option -a with value: $OPTARG" ;;
b) echo "Option -b with value: $OPTARG" ;;
*) echo "Invalid option" ;;
esac
done
shift $((OPTIND - 1)) # 移动到非选项参数
echo "Remaining arguments: $@"
执行
$ ./script.sh -a apple -b banana extra1 extra2
Option -a with value: apple
Option -b with value: banana
Remaining arguments: extra1 extra2
shift $((OPTIND - 1))
让$1
指向第一个非选项参数(即extra1
)。
总结
用法 | 作用 |
---|---|
shift | 丢弃 $1 ,将 $2 变为 $1 ,以此类推 |
shift n | 左移 n 个参数 |
while [[ $# -gt 0 ]]; do shift; done | 逐个处理所有参数 |
shift $((OPTIND - 1)) | 在 getopts 解析后跳过选项参数 |
shift
主要用于 处理脚本的命令行参数,可以逐步读取或跳过部分参数,使参数处理更加灵活。