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
相关推荐
小嘟嘟13几秒前
Kurator深度解析:云原生多集群管理的高效解决方案
linux·运维·docker·云原生·自动化
韩曙亮6 分钟前
【错误记录】VirtualBox 中安装 Ubuntu 系统无法跨虚拟机进行复制操作 ( 解决方案 - 启用 “ 共享粘贴板 “、“拖动“ 双向操作 )
linux·运维·ubuntu·virtualbox·ros 2
老王熬夜敲代码7 分钟前
IO重定向
linux·笔记
大柏怎么被偷了8 分钟前
【Linux】重定向与应用缓冲区
linux·服务器·算法
阿华hhh15 分钟前
数据结构(树)
linux·c语言·开发语言·数据结构
Bruce_Liuxiaowei16 分钟前
Mac_Linux 查询网站IP地址:4个核心命令详解
linux·tcp/ip·macos
大聪明-PLUS19 分钟前
硬件断点:它们在 Linux 中的用途和工作原理
linux·嵌入式·arm·smarc
爱吃番茄鼠骗19 分钟前
Linux操作系统———UDP/IPC网络编程
linux·网络·udp
Starry_hello world20 分钟前
Linux 线程(2)
linux
Promise48520 分钟前
关于使用wsl实现linux移植(imux6ull)的网络问题
linux·服务器·网络