簡體   English   中英

bash 腳本:如何找到“symlink/..”的絕對路徑?

[英]bash scripting: how to find the absolute path of “symlink/..”?

給定兩個文件:

generic/scripts/hello.sh
parent/scripts -> generic/scripts

從任何位置調用parent/scripts/hello.sh后,我希望(在腳本中)找到父目錄的完整路徑。 在這種情況下, parent

主要問題是parent/scripts/..指的是 unix 中的generic 另一方面,涉及正則表達式的所有內容都不是通用的,並且可能容易出錯。

不起作用的解決方案:

`dirname $0`/..
realpath  `dirname $0`/..
readlink -f `dirname $0`/..
`cd *something*/..; pwd`
`perl ... abs_path(...)`

由於符號鏈接,所有這些都將指向generic而不是parent級。

涉及正則表達式的所有內容都不是自適應/通用的,對於更復雜的路徑可能會失敗。 路徑中可能還有其他..和符號鏈接,您想要祖父母,它是一個涉及..的目錄名稱,您可以通過 $PATH 調用它...

此外,我希望它在任何情況下都能正常工作,即使它是通過$PATH調用的。

對於這個簡單的問題有什么簡單的安全解決方案嗎? 我的意思是它畢竟只是獲取父目錄!

我用了什么:

dir=$( dirname $( cd `dirname $0` >/dev/null; pwd ) )

不知道它是否完美,但它似乎表現得如預期。

嘗試這個:

basename $(dirname $(dirname $0))

或者也許只是

$(dirname $(dirname $0))

目前尚不清楚您是想要單獨的parent級還是它的完整路徑。

pushd $(dirname $0)
FOO=$(pwd)
popd

這為您提供了運行腳本的目錄的絕對路徑。

我建議 1) 使用pwd -P它將始終為您提供物理路徑,然后使用相對路徑導航到另一個地方這是最安全的。

2)使用pwd -L

我用這個來稱呼我的 scipt: ../script1並且它有一個對../relative/script2的相對調用

`(cd $0/.. && pwd)`/relative/script2

在 script1 中

在 bash 中,如果該變量可用,您可以對$PWD進行一些字符串操作

對於父目錄的路徑名,使用:

${PWD%/*}

其他示例:

me@host:/tmp/bash_string/ma ni-pu_la/tion$ echo -e \
"\$PWD or \${PWD} : " $PWD \
"\n\${PWD##/*}     : " ${PWD##/*} \
"\n\${PWD##*/}     : " ${PWD##*/} \
"\n\${PWD#/*}      : " ${PWD#/*} \
"\n\${PWD#*/}      : " ${PWD#*/} \
"\n\${PWD%%/*}     : " ${PWD%%/*} \
"\n\${PWD%%*/}     : " ${PWD%%*/} \
"\n\${PWD%/*}      : " ${PWD%/*} \
"\n\${PWD%*/}      : " ${PWD%*/} \
"\n" # Gives :
$PWD or ${PWD} :  /tmp/bash_string/ma ni-pu_la/tion 
${PWD##/*}     :  
${PWD##*/}     :  tion 
${PWD#/*}      :  tmp/bash_string/ma ni-pu_la/tion 
${PWD#*/}      :  tmp/bash_string/ma ni-pu_la/tion 
${PWD%%/*}     :  
${PWD%%*/}     :  /tmp/bash_string/ma ni-pu_la/tion 
${PWD%/*}      :  /tmp/bash_string/ma ni-pu_la 
${PWD%*/}      :  /tmp/bash_string/ma ni-pu_la/tion

那這個呢:

echo `cd .. && pwd`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM