影响启动它的交互式 shell 的脚本[重复]

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

我编写这个脚本是为了能够快速转到 ls 输出中的第 n:th 目录:

#!/usr/bin/env bash
# cd to the nth directory in a list as produced by ls
cd $( ls | head -n$1 | tail -n1 )

我将其命名为 cde 并使其可执行(它在我的 $PATH 中),所以现在我可以使用

. cde 3
例如,更改为 3:rd 目录(即我获取它)。由于 bash 如何为脚本创建子 shell,我不能像这样执行它

cde 3

因为只有子 shell 的目录受到影响。

您将如何摆脱编写额外的点并仍然获得所需的行为?

我会使用别名而不是脚本,但我不知道如何做,因为我不知道如何将参数传递给别名。

linux bash function alias subshell
1个回答
3
投票
使用函数而不是脚本或别名!

函数比别名更灵活,并且不会像执行脚本那样创建子shell。因此,目录的更改将影响您的交互式(“当前”)shell。

您可以定义一个函数来执行此操作,如下所示:

# cd to the nth directory in a list as produced by ls function cde { cd $( ls | head -n$1 | tail -n1 ) }
将函数定义放入 ~/.bash_aliases 文件(或终端启动时获取的其他文件,如 ~/.bashrc)中,这样您就不必在每个会话中手动定义它。

它会给你想要的行为。

© www.soinside.com 2019 - 2024. All rights reserved.