marcellatwin
Posts: 32
Joined: Sat Jan 27, 2018 6:41 pm
Location: USA

Issues comparing arguments of bash script

Sat Jun 15, 2019 10:02 pm

So I have a script that connects to the CAN bus with a single argument of the bus' baud rate. So I have the code below that first checks for an argument, which works just fine.

Code: Select all

# Check if argument is present
if (( "$#" == 0 )); then
	printf "\n Input Bitrate\n\n"

# Check if argument is within range
elif (( "$arg" < 0 || "$arg" > 1000 )); then
	printf "\n Bitrate Out of Range: 0 - 1000\n\n"
else
	# Shutdown link first
	sudo /sbin/ip link set can0 down
	#sudo /sbin/ip link set can1 down

	# Configure the link settings
	sudo /sbin/ip link set can0 up type can bitrate $1000 loopback on
	#sudo /sbin/ip link set can1 up type can bitrate $1000 loopback on

	# Run cansniffer
	/home/pi/linux-can-utils/cansniffer -c -l 0.1 can0
	#/home/pi/linux-can-utils/cansniffer -c -l 0.1 can1
fi
But when it checks if the value is within the correct range, it doesn't work.

Code: Select all

[email protected]:~ $ cansnif 1001
/bin/cansnif: line 22: ((: < 0 ||  > 1000 : syntax error: operand expected (error token is "< 0 ||  > 1000 ")
I've tried it a few different ways and get the same issue. I'm pretty new to scripting as well.
Any suggestions?

epoch1970
Posts: 3098
Joined: Thu May 05, 2016 9:33 am
Location: Paris, France

Re: Issues comparing arguments of bash script

Sat Jun 15, 2019 10:50 pm

I can't help you much with bash-isms, but the following would work with the regular Bourne shell

Code: Select all

#!/bin/sh
# Check if argument is present
[ "$#" -eq 0 ] && printf "\n Input Bitrate\n\n" && exit 3
# Check if argument is within range using the test built-in, '-o' OR, '-a' AND
[ "$1" -lt 0 -o "$1" -gt 1000 ] && printf "\n Bitrate Out of Range: 0 - 1000\n\n" && exit 2
# Same check using the shell's logical operators - cf. https://stackoverflow.com/a/20449796
# [ "$1" -lt 0 ] || [ "$1" -gt 1000 ] && printf "\n Bitrate Out of Range: 0 - 1000\n\n" && exit 1

printf "Do stuff with arg $1\n"
exit $?
To avoid wrangling with if/elif/else/fi the script exits early, so the bottom part is reached only if preconditions were met.
I would also avoid using too complex tests, e.g. "foo and bar or baz" they're difficult to decipher and can be fragile.
For the same reason I tend to prefer the (deprecated?) test syntax '-a'/-'o' for compound tests, and reserve the shell's '&&' and '||' operators to chaining commands.
(The scriptlet works as #!/bin/bash as well)
"S'il n'y a pas de solution, c'est qu'il n'y a pas de problème." Les Shadoks, J. Rouxel

marcellatwin
Posts: 32
Joined: Sat Jan 27, 2018 6:41 pm
Location: USA

Re: Issues comparing arguments of bash script

Mon Jun 17, 2019 6:46 pm

Thanks. Yeah so I just couldn't get it to work with the ( ) and using a more readable code like <=. So I went with your method of [ ] and the options of -gt -lt. It now works. Thanks again.

Return to “Other programming languages”