Linux shift 命令使用详解

简介

在 Bash 脚本中,shift 命令用于将命令行参数向左移动,有效地丢弃第一个参数并将其他参数向下移动。

基础语法

shell 复制代码
shift [N]

N(可选)→ 要移动的位置数。默认值为 1

示例用法

移动参数

shell 复制代码
#!/bin/bash
echo "Before shift: $1 $2 $3"

shift  # Shift once

echo "After shift: $1 $2 $3"

运行脚本示例:

shell 复制代码
./script.sh a b c d

输出如下:

shell 复制代码
Before shift: a b c
After shift: b c d
  • shift 删除 $1 (a)

  • $2 变成 $1, $3 变成 $2 等等。

在循环中使用 shift

shell 复制代码
#!/bin/bash
while [[ $# -gt 0 ]]; do
    echo "Argument: $1"
    shift
done

运行:

shell 复制代码
./script.sh one two three

输出:

shell 复制代码
Argument: one
Argument: two
Argument: three

将 shift 与 N 结合使用

shell 复制代码
#!/bin/bash
echo "Before shift: $1 $2 $3 $4"

shift 2  # Shift by 2 places

echo "After shift: $1 $2"

运行:

shell 复制代码
./script.sh a b c d

输出:

shell 复制代码
Before shift: a b c d
After shift: c d
  • $1 和 $2 都被移除

检查参数是否有剩余

shell 复制代码
#!/bin/bash
while [[ $# -gt 0 ]]; do
    echo "Processing: $1"
    shift
done
echo "No more arguments."
  • $#:剩余参数的数量

  • 当 $# 达到0时,循环结束

循环遍历成对的参数

shell 复制代码
#!/bin/bash
while [[ $# -gt 1 ]]; do
    echo "Key: $1, Value: $2"
    shift 2
done

运行:

shell 复制代码
./script.sh --name Alice --age 30 --city Parisss

输出:

shell 复制代码
Key: --name, Value: Alice
Key: --age, Value: 30
Key: --city, Value: Paris
相关推荐
进击的荆棘35 分钟前
Linux系统——库的原理与制作之ELF文件的形成与加载的过程(下)
linux·动静态库
CrazyMo_44 分钟前
鸿蒙高级——内存专用之linux-reserve-memory 方案简介
linux·运维·服务器
灯澜忆梦1 小时前
【Linux】#5 | 文件与目录基础操作命令
java·linux·运维
wuminyu1 小时前
stackChunkOop内部结构与GC屏障的配合工作原理剖析
java·linux·c语言·jvm·c++
青衫客362 小时前
从网卡到 Socket:再探 Linux 网络协议栈与 iptables 数据包处理流程
linux·网络·网络协议
承渊政道2 小时前
Linux网络学习【TCP Socket编程实战:connect的断线重连与客户端访问Linux验证】
linux·网络·学习·ubuntu·tcp·socket编程
sunoo-2292 小时前
嵌入式Linux驱动学习笔记(第3-6天):从misc封装、platform总线到设备树、中断与单总线外设实战
linux·arm开发·驱动开发·笔记·单片机·学习
雪落漂泊2 小时前
Linux基础开发工具(一)软件包管理器与Vim编辑器篇
linux·运维·服务器
崽崽..2 小时前
【Linux】网络编程的调试工具以及连接失败的具体排查方法
linux·网络
承渊政道2 小时前
CentOS 7单机部署Elasticsearch 7.17.29:从启动报错、CRUD验证到固定公网地址的完整过程
linux·elasticsearch·centos·内网穿透·cpolar·单机部署