2013-12-12 176 views
1

我想編譯一個腳本,將讀取用戶輸入,並檢查後的y/n語句文件。然後它將使文件可執行。我想用我的劇本問題是有條件的排序,但看看自己:Bash腳本 - 嵌套如果聲明如果文件不存在

target=/home/user/bin/ 

cd $target 
read -p "This will make the command executable. Are you sure? (y/n)" CONT 
if [ "$CONT" == "y" ]; 
then 
    chmod +x $1 
    echo "File $1 is now executable." 
else 
    if [ "$(ls -A /home/user/bin/)" ]; 
    then 
    echo "File not found." 
    else 
    echo "Terminating..." 
    fi 
fi 

正如我所說的,我需要的腳本打印Y/N語句之後掃描文件。該腳本工作得很好,但它仍然給出了「文件現在可執行」,即使參數文件不存在(但只是在echo'd文本後給標準系統「無法找到文件」消息)。

回答

4

你的腳本大部分是正確的,你只需要檢查文件是否先存在。另外,在shell腳本中使用cd並不是最佳實踐,這裏不需要。

所以重新寫它

#!/bin/bash 
target="/home/user/bin/$1" 

if [[ ! -f $target ]]; then 
    echo "File not found." 
else 
    read -p "This will make the command executable. Are you sure? (y/n) " CONT 
    if [[ $CONT == "y" ]]; then 
     chmod +x "$target" 
     echo "File $1 is now executable." 
    else 
     echo "Terminating..." 
    fi 
fi 
+0

Downvoted。如果你使用「#!/ bin/bash」shebang,則使用''[]''而不是'[[]]''。否則,你必須引用參數,例如''if [[! -f $ target]];''或者''if [! -f「$ target」];''。 chmod行也是錯誤的,它必須是''chmod + x「$ target」''。不要忘記''if [[$ CONT ='y']];''。 –

+0

哎呀,剛注意到一個錯字。它應該是「使用''[[]]''而不是''[]''」。我現在正在投票,因爲你已經修復了你的代碼;)如果有人沒有明白,請訪問[此鏈接](http://mywiki.wooledge.org/BashPitfalls#A.5B_.24foo_.3D_。 22bar.22_.5D) –

1

爲了得到一個認識:

  • 你的腳本將一個參數(文件的名稱)。
  • 你問你是否想讓該文件成爲可執行文件。
  • 如果答案是'是',則使文件可執行。
  • 否則,你不。

你想驗證文件是否也存在?

我想了解你的邏輯。這是什麼:

if [ "$(ls -A /home/user/bin/)" ]; 

假設要做。 [ ... ]語法是一個測試。而且,它必須是您看到的有效測試here之一。例如,有一個測試:

  • -e file:如果文件存在,則爲真。

這意味着,我可以看到,如果你的文件是/home/user/bin下:

target="/home/user/bin" 
if [ -e "$target/$file" ] # The "-e" test for existence 
then 
    echo "Hey! $file exists in the $target directory. I can make it executable." 
else 
    echo "Sorry, $file is not in the $target directory. Can't touch it." 
fi 

$(ls -A /home/user/bin/)會產生一個文件列表。這不是一個像-e這樣的有效測試,除非它發生在您的列表中的第一個文件與-e-d類似。

試着澄清你想要做什麼。我認爲這是沿着你想要的線條更多的東西:

#! /bin/bash 

target="/home/user/bin" 
if [ -z "$1" ] # Did the user give you a parameter 
then 
    echo "No file name given" 
    exit 2 
fi 

# File given, see if it exists in $target directory 
if [ ! -e "$target/$1" ] 
then 
    echo "File '$target/$1' does not exist." 
    exit 2 
fi 

# File was given and exists in the $target directory 

read -p"Do you want $target/$1 to be executable? (y/n)" continue 
if [ "y" = "$continue" ] 
then 
    chmod +x "$target/$1" 
fi 

注意我如何使用測試,如果測試失敗,我只是退出程序。這樣,我不必在if/then語句中嵌入if/then語句。

+0

Downvoted爲好。閱讀我的[評論](http://stackoverflow.com/questions/20532980/bash-script-nested-if-statement-for-if-file-doesnt-exist#comment30704265_20533317),看看爲什麼你的報價是錯誤的。 –

+0

我通常使用'[[...]]',但是'[['不是在'['是'時'test'的別名。 (他們都是BASH內置的)。對於初學者來說,使用'test'手冊是非常方便的。我會更新我的答案,以確保我所引用的所有內容。 –

+0

不,建議初學者使用''[[]]''。首先,如果他們忘記在''[[]]'中引用一個變量,那麼沒有錯誤會發生,事實上,這是正確的做法。另一個原因是人們通常會學習另一種編程語言,其中條件與「test」命令不同。所以他們會期望''[]''是一些特殊的語法,但事實並非如此。在尋求幫助時,你應該「幫助」[''。如果你想獲得所有可能的標誌列表,那麼使用''man bash''並搜索''CONDITIONAL EXPRESSIONS''。 –