Vanessa.C
Vanessa.C

Reputation: 55

Bash Shell Script errors: ambiguous redirect and unary operator expected

I'm totally new to writing code with shell script.

This is my code:

#!/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"

And this is my error:

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

Can anybody help me to understand why I having that error?

Upvotes: 1

Views: 328

Answers (1)

Fabien Bouleau
Fabien Bouleau

Reputation: 464

As @GlennJackman points out, the lines are not matching the code, hence I am guessing the following:

  • The ambiguous redirection is on line 6: To truncate a file, you should use truncate -s0 $2
  • For the unary operator error, I bet on line 21: either put a linefeed or a semicolon ; before fi

Try the following:

#!/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"

Upvotes: 1

Related Questions