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
相关推荐
宇晨T16 小时前
BurpSuite实战:WackoPicko敏感目录探测
linux·运维·服务器
月巴月巴白勺合鸟月半17 小时前
在Linux下开发桌面程序
linux·运维·服务器
zh路西法17 小时前
【tmux入门】终端分屏、SSH远程守护与一键启动脚本
linux·运维·ssh·bash
qq_1631357517 小时前
Linux 【03-pwd命令超详细教程】
linux
学途路漫漫17 小时前
Ubuntu 24.04 国内网络环境全面优化指南
linux·网络·ubuntu
c2385617 小时前
GDB 进程概念详解(下篇)—— 多进程与进阶调试能力
linux·服务器·数据库
RisunJan17 小时前
Linux命令-php(PHP语言的命令行接口)
linux·php
A_humble_scholar17 小时前
Linux(八) 进程内存全景:环境变量、main 函数参数与虚拟地址空间全链路深度解析
linux·运维·服务器
longforus17 小时前
linux上播放音乐的终极解决方案
linux·音频·折腾
xcLeigh17 小时前
鸿蒙PC平台 Shotwell 照片管理器适配实战:从 Linux GNOME 到 鸿蒙PC 的 Electron 迁移
linux·electron·harmonyos·鸿蒙·shotwell·照片管理器