2017-10-05 67 views
1

我完全不熟悉用shell script編寫代碼。Bash Shell腳本錯誤:模棱兩可的重定向和一元運算符預期

這是我的代碼:

#!/bin/bash 
echo -n "Output to $2 " 
# set counter 
count=1 
# zap output file 
> $2 
# Loop 
while [ $count -le $1 ] 
do 
    # generate some random text 
    randomnumber=`od -A n -t d -N 1 /dev/urandom` 
    randomtext=`cat /dev/urandom | tr -cd "[:alnum:]" | head -c $randomnumber` 
    # generate a random number 
    randomnumber=`od -A n -t d -N 1 /dev/urandom` 
    # output to file 
    echo "$count,$randomtext,$randomnumber" | sed -e "s: *::g" >> $2 
    # increment counter 
    count=$(($count + 1)) 
    if [ $(($count % 500)) -eq 0 ] 
    then 
echo -n "." fi 
done 
echo " Output complete" 

這是我的錯誤:

Line 2: ambiguous redirect and Line 14: unary operator expected. 

任何人可以幫助我瞭解爲什麼我具有錯誤?

+1

行號與代碼不一致。請改正。 –

+1

看起來您需要驗證用戶輸入。有2個參數被提供? –

+1

仔細閱讀[忘記在bash/POSIX shell中引用變量的安全隱患](https://unix.stackexchange.com/q/171346/4667) –

回答

1

由於@GlennJackman指出,該行不匹配的代碼,因此我猜測以下幾點:

  • 模棱兩可的重定向是第6行:要截斷一個文件,你 應該使用truncate -s0 $2
  • 對於一元操作錯誤,我敢打賭,第21行:要麼把一個換行符 或之前fi

分號;嘗試以下操作:

#!/bin/bash 
echo -n "Output to $2 " 
# set counter 
count=1 
# zap output file 
truncate -s0 $2 
# Loop 
while [ $count -le $1 ] 
do 
    # generate some random text 
    randomnumber=`od -A n -t d -N 1 /dev/urandom` 
    randomtext=`cat /dev/urandom | tr -cd "[:alnum:]" | head -c $randomnumber` 
    # generate a random number 
    randomnumber=`od -A n -t d -N 1 /dev/urandom` 
    # output to file 
    echo "$count,$randomtext,$randomnumber" | sed -e "s: *::g" >> $2 
    # increment counter 
    count=$(($count + 1)) 
    if [ $(($count % 500)) -eq 0 ] 
    then 
     echo -n "." 
    fi 
done 
echo " Output complete"