如何获取shell命令的位置参数

bla*_*ndt 0 linux bash shell

样例Bash脚本:

#!/bin/bash

echo $0
echo $1
Run Code Online (Sandbox Code Playgroud)

作为运行

$ ./prog foo
Run Code Online (Sandbox Code Playgroud)

将打印:

./prog
foo
Run Code Online (Sandbox Code Playgroud)

因此,我知道如何在Shell程序中获取位置参数。

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

mv file1 .file1.bak
Run Code Online (Sandbox Code Playgroud)

但我不想两次都不必输入file1。

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

$ echo a b c $0 $1 $2
Run Code Online (Sandbox Code Playgroud)

但是这个印

a b c -zsh
Run Code Online (Sandbox Code Playgroud)

我以为这可能只是特定于Shell的内容,因此我在中运行了它bash。

a b c bash
Run Code Online (Sandbox Code Playgroud)

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

Joa*_*ino 5

您可以使用以下之一:

!^      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
Run Code Online (Sandbox Code Playgroud)

例如:

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
Run Code Online (Sandbox Code Playgroud)

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