LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Go Back   LinuxQuestions.org > Forums > Linux Forums > Linux - Newbie
User Name
Password
Linux - Newbie This Linux forum is for members that are new to Linux.
Just starting out and have a question? If it is not in the man pages or the how-to's this is the place!

Notices

Reply
 
LinkBack Search this Thread
Old 05-26-2012, 10:45 PM   #1
samasat
LQ Newbie
 
Registered: Nov 2011
Location: San Antonio
Distribution: CentOS 6.2
Posts: 14

Rep: Reputation: Disabled
less than condition in if statement not working as desired


In following bash script I am finding that irrespective of thrdN > 10 i.e. for thrdN=12 or 24 , ${thrdN}-lt$TEN ] condition is satisfied ? What am I doing wrong ?
I wanted to ensure that always 'SimName' string has same legnth e.g. if thrdN = 2 then SOME_LONG_NAME_THRD02 and if thrdN = 12 then SOME_LONG_NAME_THRD12.
I am using centOS 6.2.
Thanks in advance,

Code:
SERIES_NAME="PerfCentOS"
PATIENT_ID="U032"
SIM_N_START=502
COUNT=0
MEM_GB=8
SCRATCH="/home/ssr/Desktop/PerfCentOS"
MESH_SRC_DIR="/home/ssr/Desktop/PerfCentOS"
ADINA_IN_SRC_DIR="/home/ssr/Desktop/PerfCentOS"
ADINA_HOME="/opt/adina/8.8.2"
TEN=10
for matN in 1 2 4 # if in series order then use like(( matN=1 ; matN<=3; matN++))
do
	for thrdN in 1 2 3 4 6 8 12 24
	do
	#Set simulation number
		SIM_N=$(($SIM_N_START + $COUNT))
		COUNT=$(($COUNT + 1))
		echo "Simulation number = ${SIM_N}"
	
	# Make directory for simulation
		if  [ ${thrdN}-lt$TEN ] 
		then
			echo " THREAD=${thrdN} less than $TEN"
			if [ $matN-lt${10} ]
			then	
			SimName="sim0${SIM_N}_${SERIES_NAME}_${PATIENT_ID}_MAT0${matN}_THRD0${thrdN}"
			else
			SimName="sim0${SIM_N}_${SERIES_NAME}_${PATIENT_ID}_MAT${matN}_THRD0${thrdN}"
			fi
		
		else 
			echo " THREAD=${thrdN} more than equal to 10"
			if [ $matN-lt${10} ]
			then	
			SimName="sim0${SIM_N}_${SERIES_NAME}_${PATIENT_ID}_MAT0${matN}_THRD${thrdN}"
			else
			SimName="sim0${SIM_N}_${SERIES_NAME}_${PATIENT_ID}_MAT${matN}_THRD${thrdN}"
			fi
		fi
		
	done
done

Last edited by samasat; 05-27-2012 at 10:53 AM. Reason: Formating correction to replace "Quote" with "Code"
 
Old 05-26-2012, 11:02 PM   #2
Ser Olmy
Senior Member
 
Registered: Jan 2012
Distribution: Slackware
Posts: 1,821

Rep: Reputation: Disabled
This works:
Code:
TEN=10
SOMETHING_ELSE=12
if [ ${SOMETHING_ELSE} -lt ${TEN} ]; then
  echo Less than 10!
fi
This does not:
Code:
TEN=10
SOMETHING_ELSE=12
if [ ${SOMETHING_ELSE}-lt${TEN} ]; then
  echo Less than 10!
fi
It would seem the if statement can't make sense of "12-lt10". I can't say I blame it.

I would recommend putting the variables inside double quotes ([ "${SOMETHING_ELSE}" -lt "${TEN}" ]), as the test will otherwise throw an error should the variable happen to be undefined or empty.
 
1 members found this post helpful.
Old 05-26-2012, 11:57 PM   #3
catkin
LQ 5k Club
 
Registered: Dec 2008
Location: Tamil Nadu, India
Distribution: Servers: Debian Squeeze and Wheezy. Desktop: Slackware64 14.0. Netbook: Slackware 13.37
Posts: 8,512
Blog Entries: 27

Rep: Reputation: 1174Reputation: 1174Reputation: 1174Reputation: 1174Reputation: 1174Reputation: 1174Reputation: 1174Reputation: 1174Reputation: 1174
Quote:
Originally Posted by Ser Olmy View Post
I would recommend putting the variables inside double quotes ([ "${SOMETHING_ELSE}" -lt "${TEN}" ]), as the test will otherwise throw an error should the variable happen to be undefined or empty.
Alternatively the more robust [[ ... ]] can be used.

The differences between [[ ... ]] and [ ... ] are detailed here.
 
Old 05-27-2012, 07:37 AM   #4
David the H.
Bash Guru
 
Registered: Jun 2004
Location: Osaka, Japan
Distribution: Debian sid + kde 3.5 & 4.4
Posts: 6,823

Rep: Reputation: 1946Reputation: 1946Reputation: 1946Reputation: 1946Reputation: 1946Reputation: 1946Reputation: 1946Reputation: 1946Reputation: 1946Reputation: 1946Reputation: 1946
Please use ***[code][/code] tags*** around your code and data, to preserve formatting and to improve readability. Please do not use quote tags, colors, or other fancy formatting.

Go back and edit your opening post to change them, please.


Actually, for integer calculations like this, ((..)) should be used instead (assuming you're using bash or ksh).

Code:
if (( SOMETHING_ELSE < TEN )); then
The benefits of this are that you can use standard math operators instead of letter-style options, and there's no need to prefix variables with "$".

The [[..]] operator is recommended for string/file tests and complex expressions.

Avoid using the old [..] test unless you specifically need POSIX-style portability.

http://mywiki.wooledge.org/ArithmeticExpression
http://mywiki.wooledge.org/BashFAQ/031
http://wiki.bash-hackers.org/commands/classictest
http://wiki.bash-hackers.org/syntax/...nal_expression


"[", being a traditional command, needs to see every entry following it as a separate argument. That means each one has to be separated by whitespace. Variables should also always be quoted to avoid problems with word-splitting.

http://mywiki.wooledge.org/BashPitfalls
(nos. 4, 7, and 10 in particular)

[[..]] and ((..)), however, are keywords, and thus allow greater flexibility in syntax (although there are still limits in what they can handle).


Finally, since environment variables are generally all upper-case, it's good practice to keep your own user variables in lower-case or mixed-case to help differentiate them. And please don't use the full "${var}" brace-enclosed variable form when you don't need it. It does nothing except cause additional typing and clutter up the code.
 
1 members found this post helpful.
Old 05-27-2012, 07:46 AM   #5
David the H.
Bash Guru
 
Registered: Jun 2004
Location: Osaka, Japan
Distribution: Debian sid + kde 3.5 & 4.4
Posts: 6,823

Rep: Reputation: 1946Reputation: 1946Reputation: 1946Reputation: 1946Reputation: 1946Reputation: 1946Reputation: 1946Reputation: 1946Reputation: 1946Reputation: 1946Reputation: 1946
By the way, from your description it looks like what you really want to do is ensure that the digit is zero-padded before using it. That can be accomplished by a simple printf command.

Code:
$ num=2
$ printf -v num '%02d' "$num"
$ echo "$num"
02
printf

Be careful not to use zero-padded numbers in arithmetic operations though, because then the shell will treat them as octal values, rather than decimals. Do the number padding just before you have to print the output.
 
Old 05-27-2012, 11:43 AM   #6
samasat
LQ Newbie
 
Registered: Nov 2011
Location: San Antonio
Distribution: CentOS 6.2
Posts: 14

Original Poster
Rep: Reputation: Disabled
Thanks Ser and Catkin.
That made my code work.
Actually earlier I tried those spaces since I was aware that there should be space after '[' and before ']' ( and now I know from David's links that in fact all variables needs space in between).

That time I tried for inner if condition as given below:
Code:
if [ ${matN} -lt ${10} ]
                        then
                        SimName="sim0${SIM_N}_${SERIES_NAME}_${PATIENT_ID}_MAT0${matN}_THRD0${thrdN}"
                        else
                        SimName="sim0${SIM_N}_${SERIES_NAME}_${PATIENT_ID}_MAT${matN}_THRD0${thrdN}"
                        fi
and its output:
Code:
Simulation number = 502
 THREAD=1 less than 10
./PerfCentOS.pbs: line 33: [: 1: unary operator expected
But now I understand that ${10} is wrong and I should have used simply 10. in fact to get around with this I used TEN=10 declaration in parent if statement.


Thanks David for you in depth help with a lot of information. The first link explains all nuances very well. Even though I have not yet grasped completely '[' and '[[' '((' I guess I understand that you mentioned in your post ( [[--]], ((--)) being bash only feature and that ((--)) facilitates use of arithmetic < , > for integers) still not clear how it really helps.

And also I sorry that out of ignorance I used wrong formating. I have corrected it now.

I attemted you suggestion by using:
Code:
        if  (( thrdN < TEN ))
                then
and it works.
Thanks for your suggestions about all caps formating convention for Environment variables and regarding "${var}". I was told by my colleague that it is safer so I was using that.

Last edited by samasat; 05-28-2012 at 10:31 AM. Reason: Correcting typo - replace old $TEN by TEN in line "with this I used $TEN=10 declaration for parent if statement."
 
Old 05-27-2012, 11:48 AM   #7
samasat
LQ Newbie
 
Registered: Nov 2011
Location: San Antonio
Distribution: CentOS 6.2
Posts: 14

Original Poster
Rep: Reputation: Disabled
you are right ..still the discussion helped me

Quote:
Originally Posted by David the H. View Post
By the way, from your description it looks like what you really want to do is ensure that the digit is zero-padded before using it. That can be accomplished by a simple printf command.

Code:
$ num=2
$ printf -v num '%02d' "$num"
$ echo "$num"
02
printf

Be careful not to use zero-padded numbers in arithmetic operations though, because then the shell will treat them as octal values, rather than decimals. Do the number padding just before you have to print the output.
Thanks David. You got my intent correct. I though printf only outputs on screen and I won't be able to get it to write to a variable string. However, I am just starting to do bash scripting and actually I am not having Linux background. So I am happy I learnt some things.

Thanks again David, Catkin and Ser.
 
Old 05-27-2012, 06:23 PM   #8
chrism01
Guru
 
Registered: Aug 2004
Location: Sydney
Distribution: Centos 6.5
Posts: 16,086

Rep: Reputation: 1994Reputation: 1994Reputation: 1994Reputation: 1994Reputation: 1994Reputation: 1994Reputation: 1994Reputation: 1994Reputation: 1994Reputation: 1994Reputation: 1994
Assign to a var
Code:
num=2
num2=$(printf '%02d' "$num")
echo $num2
 
Old 05-28-2012, 01:34 AM   #9
catkin
LQ 5k Club
 
Registered: Dec 2008
Location: Tamil Nadu, India
Distribution: Servers: Debian Squeeze and Wheezy. Desktop: Slackware64 14.0. Netbook: Slackware 13.37
Posts: 8,512
Blog Entries: 27

Rep: Reputation: 1174Reputation: 1174Reputation: 1174Reputation: 1174Reputation: 1174Reputation: 1174Reputation: 1174Reputation: 1174Reputation: 1174
Quote:
Originally Posted by samasat View Post
in fact to get around with this I used $TEN=10 declaration for parent if statement.
That should not have worked. Is it a typo for TEN=10 ?
 
Old 05-28-2012, 10:28 AM   #10
samasat
LQ Newbie
 
Registered: Nov 2011
Location: San Antonio
Distribution: CentOS 6.2
Posts: 14

Original Poster
Rep: Reputation: Disabled
thanks Chism

Quote:
Originally Posted by catkin View Post
That should not have worked. Is it a typo for TEN=10 ?
Yes, you are right Catkin ... it was a typo.... now correcting it. Code declares it as shown in the code mentioned in first post in this thread.

Thanks Chrism01 for alternative code in addition to what David suggested earlier...

Last edited by samasat; 05-28-2012 at 10:34 AM.
 
Old 05-28-2012, 11:04 AM   #11
David the H.
Bash Guru
 
Registered: Jun 2004
Location: Osaka, Japan
Distribution: Debian sid + kde 3.5 & 4.4
Posts: 6,823

Rep: Reputation: 1946Reputation: 1946Reputation: 1946Reputation: 1946Reputation: 1946Reputation: 1946Reputation: 1946Reputation: 1946Reputation: 1946Reputation: 1946Reputation: 1946
In bash, the -v option to printf saves the value to a variable instead of printing it to the screen, as the example I gave demonstrates.

Or for a fully portable version, use the command substitution technique shown by chrism01.
 
Old 06-09-2012, 05:33 PM   #12
samasat
LQ Newbie
 
Registered: Nov 2011
Location: San Antonio
Distribution: CentOS 6.2
Posts: 14

Original Poster
Rep: Reputation: Disabled
Thanks David. I have started replacing many lines with just one nice printf statement in my code.
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
BASH: IF statement not working? EdinburghLad Programming 6 05-15-2012 08:26 PM
If statement not working for testing char kayasaman Programming 12 03-27-2012 09:20 AM
Case statement in function not working cmosentine Programming 8 02-14-2012 12:24 PM
[SOLVED] if statement with md5sum not working correctly meridionaljet Linux - Newbie 2 10-01-2011 01:25 AM
[SOLVED] Or statement isn't working in script digity Linux - Newbie 8 02-09-2010 09:11 PM


All times are GMT -5. The time now is 05:12 PM.

Main Menu
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration