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
相关推荐
一个平凡而乐于分享的小比特几秒前
Linux动态库与静态库技术详解
linux·动态库·静态库
XiaoHu02071 分钟前
Linux网络编程(第三弹)
linux·运维·网络
袁袁袁袁满8 分钟前
Docker服务彻底清空的所有相关资源(容器、镜像、网络、数据卷等)
linux·运维·ubuntu·docker·容器·docker清空资源·docker停掉资源
Run_Teenage13 分钟前
Linux:匿名管道(实现个进程池)和命名管道
linux·运维·服务器
warton8813 分钟前
proxysql配置mysql mgr代理,实现读写分离
linux·运维·数据库·mysql
skywalk816313 分钟前
Ubuntu22.04安装docker并启动 dnote服务
linux·ubuntu·docker·dnote
上天_去_做颗惺星 EVE_BLUE17 分钟前
Android设备与Mac/Docker全连接指南:有线到无线的完整方案
android·linux·macos·adb·docker·容器·安卓
BingoXXZ18 分钟前
20260114Linux学习笔记
linux·服务器·笔记·学习
羊村积极分子懒羊羊18 分钟前
软件管理(网络软件仓库的使用方法)
linux
viqjeee28 分钟前
Linux ALSA驱动详解
linux·运维·服务器·alsa