bash 别名,用于运行命令(带参数)(如果存在),否则运行另一个命令(带参数)

问题描述 投票:0回答:1

我想设置 bash 别名,如果

command_1 [args]
存在且“可运行”,则运行
command_1
,或者如果
command_2 [args]
不存在或不可“运行”,则运行
command_1
[args]
事先未知,可能为空或不为空。
[args]
command_1
command_2
相同。

在终端中我可以这样操作:

command_1 --version >/dev/null 2>&1
[ "$?" = "0" ] && command_1 args || command_2 args

第一行不输出任何内容,第二行检查第一行的退出代码(

$?
)。因此,如果
command_1 --version
以“0”状态代码退出(没有错误),我运行
command_1 args
,否则(如果
command_1
不存在或因任何其他原因损坏,例如用户没有相关权限跑
command_1
)我跑
command_2 args

如何将其变成 bash 别名?

如果没有

[args]
我可以使用这样的东西:

alias my_alias='command_1 --version >/dev/null 2>&1 ; [ "$?" = "0" ] && command_1 || command_2'

但是在这种情况下,如果我运行

my_alias args
并且
command_1
存在,它将在没有参数的情况下运行
command_1
。如何将
[args]
添加到我的
command_1
command_2
的别名中?

linux bash alias
1个回答
0
投票

创建一个脚本并使用别名指向它,例如:

root:@/tmp$ cat foo.sh
#!/usr/bin/env bash
echo "$@"
root:@/tmp$ chmod +x foo.sh
root:@/tmp$ alias myalias="$(pwd)/foo.sh"
root:@/tmp$ myalias 1
1
root:@/tmp$ cd /var && myalias 1 2 3
1 2 3

你的脚本应该是这样的:

#!/usr/bin/env bash
command_1 --version >/dev/null 2>&1
[ "$?" = "0" ] && command_1 "$@" || command_2 "$@"
© www.soinside.com 2019 - 2024. All rights reserved.