2016-11-27 87 views
2

我剛寫了一個腳本,等待用戶的路徑。我使用read在bash變量目錄中刪除「/」

爲了更加便於用戶使用,您可以使用選項卡來完成路徑(如果存在該路徑)。

我的問題是:如果文件存在,"/"字符串被添加到行尾。所以,我只是想刪除它,我在這裏和在互聯網上搜索,我發現這一點:

echo ${str::-1) 

所以我用一個簡單的迭代中使用它(如果找到"/"末再刪除),但它退還給我:"str is a directory..."當我運行腳本作爲錯誤消息。

下面是一個例子:

read -e -p "Where do you want to install it ? 
Install directory : " _installdir 

echo "$_installdir" 
_slashdel=echo "$_installdir" |tail -c 1 
echo -e "$_slahdel" #just used for debug here 
if [ "$_slahdel" = "/" ]; 
then 
     echo "{echo _installdir::-1}" 
fi 
echo "install dir :" "$_installdir" 

回答

1

如果你想要去除可選尾隨/,最好使用${str%/}

read -e -p "Where do you want to install it ? 
Install directory : " _installdir 

_installdir=${_installdir%/} 
echo "install dir : $_installdir" 

不僅是簡單的,但如果沒有尾隨/,那麼它將保持原始值。 因此,您不需要像在原始腳本中使用的if語句。

您可以瞭解更多關於字符串操作中的Bash這裏:

http://www.tldp.org/LDP/abs/html/string-manipulation.html

順便說一句,你的劇本是完全錯誤的。您可以在shellcheck.net上驗證腳本的完整性。

+0

Thx man !!它解決了我的問題,併爲這些信息thx :) – Shrom

0

大部分代碼都是不相關的(您正在測試_slahdel,與_slashdel不一樣)。

該錯誤消息來源於此部分(你應該已經找到了自己的涅槃的代碼):

_slashdel=echo "$_installdir" 

這是告訴bash到_slashdel組運行命令$_installdir與環境變量echo。由於$_installdir是一個目錄,因此無法運行,因此出現錯誤。

0
read -e -p "Where do you want to install it ? 
Install directory : " _installdir 

echo "$_installdir" 
_slashdel=$(echo -n "$_installdir" |tail -c 1) 
echo -n "$_slashdel" #just used for debug here 
if [ "$_slashdel" = "/" ]; 
then 
     _installdir="${_installdir::-1}" 
fi 
echo "install dir :" "$_installdir" 
+0

thx老兄:)很多:) – Shrom