2012-11-09 75 views
-1

在unix shell(特別是Ubuntu)中將目錄更改爲從ls命令打印的第x個目錄中有沒有辦法? 我知道你可以用多種方式對目錄進行排序,但是使用ls的輸出來獲取第x個目錄?更改爲第x個目錄終端

一個例子殼:

$ ls 
$ first_dir second_dir third_really_long_and_complex_dir 

在我想要通過使圖3(或2適當陣列格式)移動到third_really_long_and_complex_dir。 我知道我可以簡單地複製和粘貼,但如果我已經在使用鍵盤,那麼鍵入「cdls 2」之類的東西就比較容易,或者如果我知道索引。

回答

0

交互式會話中cd的主要問題是您通常需要更改正在處理命令提示符的shell的當前目錄。這意味着啓動一個子shell(例如腳本)將無濟於事,因爲調用任何cd都不會影響父shell。

但是,根據您使用的是哪個外殼,您可能可以定義一個函數來執行此操作。例如在bash:

function cdls() { 
    # Save the current state of the nullglob option 
    SHOPT=`shopt -p nullglob` 

    # Make sure that */ expands to nothing when no directories are present 
    shopt -s nullglob 

    # Get a list of directories 
    DIRS=(*/) 

    # Restore the nullblob option state 
    $SHOPT 

    # cd using a zero-based index 
    cd "${DIRS[$1]}" 
} 

注意,在這個例子中,我絕對不能解析的lsfor a number of reasons輸出。相反,我讓外殼本身檢索目錄列表(或目錄鏈接)...

這就是說,我懷疑使用此功能(或任何對此效果)是一種非常好的方法來設置自己一個巨大的混亂 - 就像在使用rm後改爲錯誤的目錄。文件名自動完成已經足夠危險,不必強迫自己計數 ...

+0

這在我的系統上出色地工作。謝謝 –