首页 > 解决方案 > 如何获取shell命令的位置参数

问题描述

示例 Bash 脚本:

#!/bin/bash

echo $0
echo $1

运行这个

$ ./prog foo

会打印:

./prog
foo

所以我知道如何在 shell 程序中获取位置参数。

我想弄清楚的是如何对任何其他 shell 命令执行相同的操作。比如mv,我想说

mv file1 .file1.bak

但我不想两次都输入 file1 。

我尝试了与上面的 shell 脚本相同的方法。

$ echo a b c $0 $1 $2

但这印

a b c -zsh

我认为它可能只是一个特定于 shell 的东西,所以我在bash.

a b c bash

TL;DR:如何从扩展中的 shell 命令中获取位置参数?

标签: linuxbashshell

解决方案


您可以使用以下方法之一:

!^      first argument
!$      last argument
!*      all arguments
!:2     second argument

!:2-3   second to third arguments
!:2-$   second to last arguments
!:2*    second to last arguments
!:2-    second to next to last arguments

!:0     the command
!!      repeat the previous line

前任:

echo a b c d e
> a b c d e
echo !$
> echo e
> e
echo "a" "b" "c" "d" "e"
> a b c d e
echo "!:2"
> echo ""b""
> b

这些是操纵bash 历史的命令。


推荐阅读