After reading a ton of documentation and multiple SO solutions, I still cannot get the right syntax for multiple conditions in a while loop with the read line command.
I tried the following stack overflow solution below to no avail.
Bash scripting, multiple conditions in while loop
!/bin/bash
while (( $(read -r line) && "$1" != 1 ))
do
#Do stuff
done < myFile.txt
The error I am getting is ((: && 8 != 1 : syntax error: operand expected (error token is "&& 8 != 1 "
Also tried read -r line
instead of wrapping it in the $
sign and still did not work.
Where did I go wrong?
EDIT: Ignore the logic of my original post. That will eventually get changed. I'm just trying to find out the proper syntax.
I think that the correct syntax here would be:
#!/bin/bash
while read -r line && (( "$1" != 1 ))
do
# some stuff
done < myFile.txt
The read
command needs to go outside of the (( ))
if you want the loop to run as long as read
is successful. That said, I'm not sure about the conditions you're using, as $1
is the first argument passed to your script, which won't ever change in the script you've shown us.
The syntax of a while
loop is while compound_list do_group
1 .
Where a compound_list
is any valid sequence of commands basically.
Your current attempt is trying to stick commands/etc. inside an arithmetic expression which is why you are getting a syntax error. Neither of the bits of your compound_list
are arithmetic expressions though (the second one could be but doesn't need to be).
So you want something more like this
while read -r line && [ "$1" != 1 ]
or to keep the arithmetic expression instead of the [
like this
while read -r line && (( "$1" != 1 ))
That being said, and as Tom Fenech indicated in his comment on the post, nothing in the code you've shown us will ever cause the value of $1
to change. So what exactly is that bit of the test supposed to be doing?
The problem you had following the advice in the answer you linked is that you didn't pay attention to where the various types of brackets/parentheses/etc. went and what they meant (the answer didn't explain them) and none of the conditions in that question were commands themselves.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.