网站首页 > 精选文章 / 正文
简介
在 Bash 脚本中,shift 命令用于将命令行参数向左移动,有效地丢弃第一个参数并将其他参数向下移动。
基础语法
shift [N]
N(可选)→ 要移动的位置数。默认值为 1
示例用法
移动参数
#!/bin/bash
echo "Before shift: $1 $2 $3"
shift # Shift once
echo "After shift: $1 $2 $3"
运行脚本示例:
./script.sh a b c d
输出如下:
Before shift: a b c
After shift: b c d
- shift 删除 $1 (a)
- $2 变成 $1, $3 变成 $2 等等。
在循环中使用 shift
#!/bin/bash
while [[ $# -gt 0 ]]; do
echo "Argument: $1"
shift
done
运行:
./script.sh one two three
输出:
Argument: one
Argument: two
Argument: three
将 shift 与 N 结合使用
#!/bin/bash
echo "Before shift: $1 $2 $3 $4"
shift 2 # Shift by 2 places
echo "After shift: $1 $2"
运行:
./script.sh a b c d
输出:
Before shift: a b c d
After shift: c d
- $1 和 $2 都被移除
检查参数是否有剩余
#!/bin/bash
while [[ $# -gt 0 ]]; do
echo "Processing: $1"
shift
done
echo "No more arguments."
- $#:剩余参数的数量
- 当 $# 达到0时,循环结束
循环遍历成对的参数
#!/bin/bash
while [[ $# -gt 1 ]]; do
echo "Key: $1, Value: $2"
shift 2
done
运行:
./script.sh --name Alice --age 30 --city Parisss
输出:
Key: --name, Value: Alice
Key: --age, Value: 30
Key: --city, Value: Paris
Tags:linux移动命令
猜你喜欢
- 2025-04-06 Linux编辑命令vim(linux编辑命令vim文件最底)
- 2025-04-06 Linux 命令 mv (文件管理)——想玩转linux就请一直看下去
- 2025-04-06 parted命令详解(parted命令分区)
- 2025-04-06 常用linux命令:find(常用linux命令20个)
- 2025-04-06 作为Linux初学者,这25个命令一定要会!
- 2025-04-06 Linux内置命令帮助方式(linux系统帮助命令有哪些?)
- 2025-04-06 linux基本功系列之mv命令实战(linux mv命令详解)
- 2025-04-06 Linux系统中玩到让你停不下来的命令行游戏
- 2025-04-06 能够ping通服务器的同时端口不通的排查方法
- 2025-04-06 Linux命令学习——MV命令(linux mv命令的用法)