Reputation: 89
Loop does not work normally in git action.
My task.sh looks like this:
#!/bin/bash
range=100
number=$((RANDOM % range))
while [ "$i" -le "$number" ]; do
echo "DATE: $1" >> date.txt
done
The result of the above code is:
./task.sh: 6: [: Illegal number:
The code below works fine.
echo "DATE: $1" >> date.txt
I tried the following, but it also gives an error.
#!/bin/bash
range=500
number=$((RANDOM % range))
for ((run=1; run <= number; run++)); do
echo 'hello'
done
I'm curious how you can make a command like below work normally.
while (random(1-100)); do
echo 'hello'
done
Best regards!
Upvotes: 1
Views: 495
Reputation: 1326782
It should work fine with:
while [[ "$i" -le "$number" ]]; do
^^ ^^
This requires bash, but since your shebang is #!/bin/bash
, your t.sh
script will run with bash, no matter its '.sh
' extension.
But in its current form, it would be an infinite loop.
You would need to add
i=$((i+1))
That would increment the $i
variable, making "$i" -le "$number"
work properly.
Initializing i
to 0 is better/cleaner, but [[ "" -le "$number" ]]
(on the first loop, still "works" (in that an empty string is consider "lower or equal" to an non-empty "$number
" string, and remains in the loop)
That being said, the more correct form/usage for that script would be (using arithmetic comparison):
#!/bin/bash
range=100
number=$((RANDOM % range))
i=0
while (( i <= number )); do
echo "DATE: ${i}" >> date.txt
i=$((i+1))
done
Or, using a c-style loop
#!/bin/bash
range=100
number=$((RANDOM % range))
for ((i = 0 ; i < number ; i++)); do
echo "DATE: ${i}" >> date.txt
done
All this assumes bash
, but as seen here, since for (( ... ))
syntax isn't POSIX, it would not work with Alpine Linux or other OS where sh
links to ash (Almquist shell) or Dash.
In that latter case:
#!/bin/bash
range=100
number=$((RANDOM % range))
for i in $(seq 0 $number); do
echo "DATE: ${i}" >> date.txt
done
Upvotes: 3
Reputation: 123560
You have two separate problems:
sh
, not bash
i
For the first one, see Why does my Bash code fail when I run it with 'sh'?
For the second, set i=0
in your script before you try to compare $i
as a number.
Upvotes: 2