2014-01-21 152 views
3

我正在編寫一個腳本來刪除目錄中的所有文件以供練習。我使用引號我的變量,但我仍然得到以下錯誤:bash中太多參數錯誤

/usr/local/bin/deleteall: line 6: [: too many arguments 
/usr/local/bin/deleteall: line 11: [: too many arguments 

這裏是我的代碼:

#!/bin/bash 
#Deletes all files in the current directory 

read -p "You are about to delete all files in $(pwd). Are you sure you want to do this? y/n" yn 
echo $yn 
if [ [ "$yn" = "y" ] -o [ "$yn" = "Y" ] ] ; then 
     for i in `ls`; do 
       rm $i 
     done 
     exit; 
elif [ [ "$yn" = "n" ] -o [ "$yn" = "N" ] ] ; then 
     exit; 
else 
     read -p "Please enter y (yes) or n (no)" 
     exit; 
fi 

這是整個輸出:

You are about to delete all files in <my dir>. Are you sure you want to do this? y/nn 
n 
/usr/local/bin/deleteall: line 6: [: too many arguments 
/usr/local/bin/deleteall: line 11: [: too many arguments 
Please enter y (yes) or n (no)n 

我在做什麼錯?

回答

5

此行似乎是問題:

if [ [ "$yn" = "y" ] -o [ "$yn" = "Y" ] ] ; then 

你可以取代這個:

if [[ "$yn" == [yY] ]]; then 

PS:做同樣的,你檢查n or N行。

+0

謝謝!這解決了它。爲什麼我的原始代碼沒有工作? –

+2

@WilliamOliver:因爲你的語法不正確。它應該是:'[「$ yn」='y'-o「$ yn」='Y']' – anubhava

+0

@mrjink不在Bash條件中 –

0

這是你想要什麼:

read -p "Are you sure? " -n 1 -r 
echo # (optional) move to a new line 
if [[ $REPLY =~ ^[Yy]$ ]] 
then 
    for i in `ls`; do 
     rm -rf $i 
done 
fi 

if [[ $REPLY =~ ^[Nn]$ ]] 
then 
    #do what you want 
done 
fi 
2

不能嵌套[]。它將字面上的嵌套括號解釋爲參數,並打印出一個錯誤,這個錯誤太多了。

就在這個將採用雙支架和相同的邏輯

if [[ $yn == "y" || $yn == "Y" ]]; then 

而且工作

if [ "$yn" = "y" -o "$yn" = "Y" ]; then 

另一個替代語法

for i in `ls`; do 
    rm $i 
done 

真的應該

for i in *; do 
    [ -f "$i" ] && rm $i 
done 

因此,它只會嘗試刪除常規文件(除非您重寫了rm,並且您可以決定對符號鏈接執行什麼操作,否則您將得到dirs錯誤)。而ls只是無關緊要的。

+0

有沒有辦法在Bash中做嵌套條件? –

+1

@WilliamOliver據我所知,並不是我所能想到的,但我無法想象這會是一個問題。只需使用和/或和它們各自的符號,或者嵌套有條件的塊。 – BroSlow

+1

「嵌套條件」實際上並不合理。我認爲你正在尋找分組,這可以用圓括號來完成:'if [[(「$ yn」=「y」)|| (「$ yn」=「Y」)]]; then'。但是,因爲'['是常規命令,所以如果使用該命令而不是'[[',則必須轉義括號:'if [\(「$ yn」=「y」\)-o \(「$ yn 「=」Y「\)]; then'。 –