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
相关推荐
屎派克9 分钟前
linux和windows是采用何种机制保存密码的?
linux·运维·服务器
张小九9919 分钟前
Linux修改默认shell为zsh
linux·运维·服务器
竹之却37 分钟前
【云服务器】在 Linux(Ubuntu / CentOS 7)上快速搭建我的世界 Minecraft 服务器,并实现远程联机,详细教程
linux·服务器·ubuntu·腾讯云·我的世界服务器搭建
知忆_IS42 分钟前
【问题解决】Linux安装conda修改~/.bashrc配置文件后,root 用户下显示 -bash-4.2#
linux·conda·bash
Claus-1 小时前
进程间通信—system v标准
linux·运维·jvm
musk12122 小时前
ubuntu 安装 g++
linux·运维·ubuntu
徐小黑ACG2 小时前
Ubuntu下载docker、xshell
linux·ubuntu·docker
vortex53 小时前
如何为 Debian 和 Kali 系统更换软件源并更新系统
linux·运维·网络·网络安全·渗透测试·debian·kali
大明者省3 小时前
Xshell远程登录腾讯云高性能应用服务
linux·服务器·腾讯云
程序猿本员3 小时前
1.深入浅出gcc/g++编译链接过程
linux·c++