这个问题我也确实有一段时间了,尤其是对于这种常见的情况:
$ mkdir folder
$ cd folder
我已经为这个特殊情况做了一个小别名:
function mkcd()
{
mkdir "$1" && cd "$1"
}
$ mkcd folder
但是有两个问题让我对这个别名感到“沮丧”:
- 这是一个更大问题的特例 (mkdir);
- 这不是“直观的”:一般来说,在我意识到我需要它的那一刻,我已经输入了:
$ mkdir folder;所以,为了使用我的别名,我必须回退一个字,然后删除 mkdir 的最后 3 个字符,然后替换为 cd,然后......然后我放弃了,因为输入 @987654326 更快@...
所以当我读到你的问题时,它让我想写一些更好的东西,你可以在行尾添加一些东西(之前不必考虑它),它可以与任何其他命令一起使用,而不仅仅是 @ 987654327@.
这是一个函数(我称之为cdd),您只需在行尾附加("<cmd> ; cdd")即可启动当前命令,然后将当前路径更改为最后一个参数command 是目录的路径。
示例:
/etc $ cp fstab /tmp; cdd # --> current dir = /tmp
/tmp $ ...
另一个:
~ $ mkdir "some proj/src" -p; cdd # --> current dir = some proj/src
~/some proj/src $ ...
它不是完美没有错误,而且相当棘手,但效果很好(欢迎任何评论):
代码:
# Change the current path to the last directory used as an argument inside a
# bash command line.
#
# Bash only.
# This function MUST be used at the end of a single command line, like this:
# $ <any command> ; cdd
# <any command> is any command with any argument(s), including at least one path
# to an existing directory.
# It handles dir names with spaces and quoted dir names
#
# Ex. :
# /etc $ cp fstab /tmp; cdd # --> current dir = /tmp
# /tmp $ ...
#
# ~ $ mkdir "some proj/src" -p; cdd # --> current dir = ~/some proj/src
# ~/some proj/src $ ...
function cdd()
{
local last_com stripped args nb_args arg last_dir i
# Get the current command from the history:
last_com="$(history|tail -n1|sed -n 's/^\s*[0-9]*\s*//p')"
# IMPORTANT: if you want to change to name of the function, you have to
# change it as well in the regex just below:
# Strip the call of 'cdd' function at the end:
stripped="$(echo "$last_com"|sed -n 's/;\s*cdd\s*$//p')"
# Split the command arguments:
eval "args=( $stripped )"
nb_args=${#args[@]}
[[ $nb_args == 0 ]] && return
# Look for the last directory used as an argument:
for (( i = nb_args - 1; i != 0; i-- )); do
arg="${args[$i]}"
if [[ -d $arg ]]; then
last_dir="$arg"
break
fi
done
# If found, change current directory:
[[ -n $last_dir ]] && cd "$last_dir"
}