1

I am trying to insert names and numbers in a text file. I have wrote a short script for the learning purpose.

v= expr $# % 2
echo $v
if [ "$v" -eq 0 ]; then
    i=1
    while [ "$i" -lt $# ]
    do
        echo "$i    $i+1" >> database
        i=$((i+1))
    done
echo "User(s) successfully added \n\v"
else
    echo "Arguments are not complete";
fi

When i enter two arguments, the shell output is as follows

0                     # (The value of variable v)
./myscript: line 3: [: : integer expression expected
Arguments are not complete  # (else statement is executed)

When i replace -eq to == in line 3 (if statement), error msg is gone but still the IF statement doesn't execute as i expect.

0              # (output of variable v)
Arguments are not complete # (else statement is executed)

2 Answers 2

3

You need to enclose the variable assignment in $(...) ("command substitution"):

v=$(expr $# % 2)

In the if statement, -eq should be correct. Also, to make sure it works, I would use double square brackets (this might depend on the shell you use):

if [[ ${v} -eq 0 ]]; then

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, I have added double brackets in the IF statement and it worked. Kindly explain whats the difference in the single and double brackets in if statement. I also want to read the arguments passed to the script. I want to read it in such manner e.g for i = 1, $($i) should read $1 (argument first).
The difference between single and double brackets is nicely explained here: (serverfault.com/questions/52034/…) Your idea for the for loop is almost complete, you just need a sequence to iterate over, you can also do this with command substitution: for i in $(seq 1 $#); do <code> ; done
0

The immediate problem is the failure to use command substitution to capture the result of the expr command: v=$( expr $# % 2 ). However, expr is no longer needed for arithmetic; use an arithmetic expression just as you did to increment i.

v=$(( $# % 2 ))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.