Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell script: if statement

I'm following the tutorial here: http://bash.cyberciti.biz/guide/If..else..fi#Number_Testing_Script

My script looks like:

lines=`wc -l $var/customize/script.php`
if test $lines -le 10
then
    echo "script has less than 10 lines"
else
    echo "script has more than 10 lines"
fi

but my output looks like:

./boot.sh: line 33: test: too many arguments
script has more than 10 lines

Why does it say I have too many arguments? I fail to see how my script is different from the one in the tutorial.

like image 995
dukevin Avatar asked Jun 12 '12 08:06

dukevin


People also ask

Can we use if in shell script?

Conditions in Shell ScriptsAn if-else statement allows you to execute iterative conditional statements in your code. We use if-else in shell scripts when we wish to evaluate a condition, then decide to execute one set between two or more sets of statements using the result.

What is $? == 0 in shell script?

$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded. The grep manpage states: The exit status is 0 if selected lines are found, and 1 if not found.

What is in if statement in Bash script?

The COMMANDS gets executed if the CONDITION evaluates to True. Nothing happens if CONDITION returns False; the COMMANDS are ignored. Example: The following is an example script that will prompt you to input a number and then it checks whether the given number is even.

What is == in shell script?

== operator is the operator that equates the values of two operators. It returns true if the values are equal and returns false otherwise. != operator is the operator that equates the values of two operators and check for their inequality.


2 Answers

wc -l file command will print two words. Try this:

lines=`wc -l file | awk '{print $1}'`

To debug a bash script (boot.sh), you can:

$ bash -x ./boot.sh

It'll print every line executed.

like image 198
kev Avatar answered Sep 23 '22 09:09

kev


wc -l file

outputs

1234 file

use

lines=`wc -l < file`

to get just the number of lines. Also, some people prefer this notation instead of backticks:

lines=$(wc -l < file)

Also, since we don't know if $var contains spaces, and if the file exists:

fn="$var/customize/script.php"
if test ! -f "$fn"
then
    echo file not found: $fn
elif test $(wc -l < "$fn") -le 10
then
    echo less than 11 lines
else
    echo more than 10 lines
fi
like image 42
mvds Avatar answered Sep 24 '22 09:09

mvds