[英]Bash alias utilizing the command inputs
我想創建一個bash別名來執行以下操作:
假設我位於以下路徑:
/dir1/dir2/dir3/...../dirN
我想不使用cd ..
就直接上dir3。 我將只寫cdd dir3
,它應該直接轉到/dir1/dir2/dir3
。 cdd
是我的別名。
我寫了以下別名,但是不起作用:
alias cdd='export newDir=$1; export myPath=`pwd | sed "s/\/$newDir\/.*/\/$newDir/"`; cd $myPath'
簡單地說,它應該獲取當前的完整路徑,然后在新的目標目錄之后刪除所有內容,然后cd到該新路徑
我的命令的問題是$1
無法獲得我對命令cdd
輸入
我認為這是一個稍微簡單的功能,可以實現您要執行的操作:
cdd() { cd ${PWD/$1*}$1; }
說明:
${PWD/$1*}$1
獲取當前工作目錄,並在將字符串傳遞給目標目錄之后剝離所有內容,然后將該字符串添加回去。 然后將其用作cd
的參數。 我沒有理會添加任何錯誤處理,因為cd
會自行處理。
例:
[atticus:pgl]:~/tmp/a/b/c/d/e/f $ cdd b
[atticus:pgl]:~/tmp/a/b $
這有點丑陋,但有效。
這是一個函數-您可以將其放置在shell配置文件中-它可以完成您想要的; 請注意,除了目錄名稱外 ,它還支持級別 (例如, cdd 2
在層次結構中上升了2級); 僅使用cdd
就會上移到父目錄。
另請注意,匹配不區分大小寫。
該代碼取自“ 如何用制表符替換命令行參數? ”,您還將在其中找到一種方法來為原始目錄名添加互補的制表符補全。
cdd ()
{
local dir='../';
[[ "$1" == '-h' || "$1" == '--help' ]] && {
echo -e "usage:
$FUNCNAME [n]
$FUNCNAME dirname
Moves up N levels in the path to the current working directory, 1 by default.
If DIRNAME is given, it must be the full name of an ancestral directory (case does not matter).
If there are multiple matches, the one *lowest* in the hierarchy is changed to." && return 0
};
if [[ -n "$1" ]]; then
if [[ $1 =~ ^[0-9]+$ ]]; then
local strpath=$( printf "%${1}s" );
dir=${strpath// /$dir};
else
if [[ $1 =~ ^/ ]]; then
dir=$1;
else
local wdLower=$(echo -n "$PWD" | tr '[:upper:]' '[:lower:]');
local tokenLower=$(echo -n "$1" | tr '[:upper:]' '[:lower:]');
local newParentDirLower=${wdLower%/$tokenLower/*};
[[ "$newParentDirLower" == "$wdLower" ]] && {
echo "$FUNCNAME: No ancestral directory named '$1' found." 1>&2;
return 1
};
local targetDirPathLength=$(( ${#newParentDirLower} + 1 + ${#tokenLower} ));
dir=${PWD:0:$targetDirPathLength};
fi;
fi;
fi;
pushd "$dir" > /dev/null
}
我同意mklement0,這應該是一個函數。 但是比較簡單。
將此添加到您的.bashrc
:
cdd () {
newDir="${PWD%%$1*}$1"
if [ ! -d "$newDir" ]; then
echo "cdd: $1: No such file or directory" >&2
return 1
fi
cd "${newDir}"
}
請注意,如果$1
(您的搜索字符串)在路徑中出現多次,則此函數將首選第一個。 還要注意,如果$1
是路徑的子字符串,則不會找到它。 例如:
[ghoti@pc ~]$ mkdir -p /tmp/foo/bar/baz/foo/one
[ghoti@pc ~]$ cd /tmp/foo/bar/baz/foo/one
[ghoti@pc /tmp/foo/bar/baz/foo/one]$ cdd foo
[ghoti@pc /tmp/foo]$ cd -
/tmp/foo/bar/baz/foo/one
[ghoti@pc /tmp/foo/bar/baz/foo/one]$ cdd fo
cdd: fo: No such file or directory
如果您想通過運行cdd 2
來包括將功能提高2個級別的功能,則可能會起作用:
cdd () {
newDir="${PWD%%$1*}$1"
if [ "$1" -gt 0 -a "$1" = "${1%%.*}" -a ! -d "$1" ]; then
newDir=""
for _ in $(seq 1 $1); do
newDir="../${newDir}"
done
cd $newDir
return 0
elif [ ! -d "$newDir" ]; then
echo "cdd: $1: No such file or directory" >&2
return 1
fi
cd "${newDir}"
}
long if
語句驗證您提供的整數本身不是目錄。 我們構建了一個新的$newDir
以便您可以進行cd -
如果需要,可以返回到原始位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.