我曾经使用CShell(csh),它允许您创建一个接受参数的别名。符号有点像

alias junk="mv \\!* ~/.Trash"

在巴什,这似乎行不通。鉴于Bash有许多有用的特性,我会假设这一特性已经实现,但我想知道如何实现。


当前回答

Bash别名不直接接受参数。您必须创建一个函数。

alias不接受参数,但可以像别名一样调用函数。例如:

myfunction() {
    #do things with parameters like $1 such as
    mv "$1" "$1.bak"
    cp "$2" "$1"
}


myfunction old.conf new.conf #calls `myfunction`

顺便说一句,.bashrc和其他文件中定义的Bash函数可以作为shell中的命令使用。例如,您可以这样调用前面的函数

$ myfunction original.conf my.conf

其他回答

有一次我做了一些有趣的项目,我仍然在使用它。它显示了一些动画,而我通过cp命令复制文件,因为cp没有显示任何内容,这有点令人沮丧。所以我取了这个别名

alias cp="~/SCR/spiner cp"

这是spiner脚本

#!/bin/bash

#Set timer
T=$(date +%s)

#Add some color
. ~/SCR/color

#Animation sprites
sprite=( "(* )  ( *)" " (* )( *) " " ( *)(* ) " "( *)  (* )" "(* )  ( *)" )

#Print empty line and hide cursor
printf "\n${COF}"

#Exit function
function bye { printf "${CON}"; [ -e /proc/$pid ] && kill -9 $pid; exit; }; trap bye INT

#Run our command and get its pid
"$@" & pid=$!

#Waiting animation
i=0; while [ -e /proc/$pid ]; do sleep 0.1

    printf "\r${GRN}Please wait... ${YLW}${sprite[$i]}${DEF}"
    ((i++)); [[ $i = ${#sprite[@]} ]] && i=0

done

#Print time and exit
T=$(($(date +%s)-$T))
printf "\n\nTime taken: $(date -u -d @${T} +'%T')\n"

bye

看起来像这样

循环动画)

这里是上面提到的彩色脚本的链接。和新的动画周期)

您所要做的就是在别名中生成一个函数:

$ alias mkcd='_mkcd(){ mkdir "$1"; cd "$1";}; _mkcd'
             ^        *      ^  ^     ^  ^         ^

您必须在“$1”周围加双引号,因为单引号不起作用。这是因为在标有箭头的地方出现引号冲突会混淆系统。此外,在标有星号的位置需要一个空间用于该功能。

以下是示例:

alias gcommit='function _f() { git add -A; git commit -m "$1"; } ; _f'

非常重要:

{后和{前有一个空格。有一个;依次在每个命令之后。如果您在最后一个命令后忘记了这一点,您将看到>提示符!参数用引号括起来,如“$1”

我会发布我的(希望是好的)解决方案(对于未来的读者,最重要的是编辑)。所以,请编辑并改进/删除本文中的任何内容。

在终端中:

$ alias <name_of_your_alias>_$argname="<command> $argname"

并使用它(注意“_”后面的空格:

$<name_of_your_alias>_ $argname

例如,cat文件hello.txt的别名:

(别名为CAT_FILE_)$f(是$argname,在本例中是一个文件)

$ alias CAT_FILE_$f="cat $f"

$ echo " " >> hello.txt
$ echo "hello there!" >> hello.txt
$ echo " " >> hello.txt
$ cat hello.txt

    hello there!

测试(注意“_”后面的空格):

CAT_FILE_ hello.txt

要获取参数,应该使用函数!

然而,$@在创建别名时得到解释,而不是在执行别名期间得到解释,并且转义$也不起作用。我如何解决这个问题?

您需要使用shell函数而不是别名来解决此问题。您可以如下定义foo:

function foo() { /path/to/command "$@" ;}

OR

foo() { /path/to/command "$@" ;}

最后,使用以下语法调用foo():

foo arg1 arg2 argN

确保将foo()添加到~/.bash_profile或~/.zshrc文件中。

在你的情况下,这会奏效的

function trash() { mv $@ ~/.Trash; }