i have "if" loop and want that in my "then" part the command will be "jump back to line...and run the script all over from that line". how do I write it
if [ -s file.txt ]
then
jump to command \ jump to line ....
else
<command>
fi
thanks
CodePudding user response:
How to avoid goto
and start processing from a certain point? As an example you want to start over the processing until a flag has value 5.
The comments mentioned a loop
. A dirty loop is something like this:
startfrom=0
flag=0
# Dirty loop, look to second code fragment for cleanup
while :; do
if ((startfrom==0)); then
echo "First time, all statements"
((startfrom ))
fi
if ((startfrom==1)); then
echo "Starting from line labelled 1"
((startfrom ))
((flag ))
fi
echo "Flag=$flag"
if ((flag<5)); then
echo "Simulating goto line labelled 1"
startfrom=1
continue
fi
echo "The End"
break
done
Before you think "Ok, that is the goto I wanted. What a load of overhead you need in bash", look at the second implementation.
process_flag() {
((flag ))
echo "Flag=$flag"
if ((flag<5)); then
echo "Need to process again"
return 0
fi
return 1
}
flag=0
echo "First time, all statements"
while :; do
process_flag || break
done
echo "The End"
This already looks better. When the function is small, you can put everything in the loop
.
flag=0
echo "First time, all statements"
while :; do
((flag ))
echo "Flag=$flag"
if ((flag<5)); then
echo "Need to process again"
continue
else
break
fi
done
echo "The End"
Is this example you can use a different loop
. Before writing statements for each step, look at the structure and think what control functions you need. Perhaps you want a simple
echo "First time, all statements"
for ((flag=1; flag<=5; flag )); do
echo "Flag=$flag"
if ((flag<5)); then
echo "Need to process again"
fi
done
echo "The End"
When your loop
has more lines than your screen, consider using a function for the small details.
CodePudding user response:
(Note: this is a terrible idea)
The shell doesn't give you a goto, but you can fabricate one!
#!/bin/bash
echo executing before label
# label:
goto() {
target="$1"
shift
exec sh -c "$(sed -e "1,/^# $target:$/d" $0)" "$0" "$@"
}
echo executing from label args: $@
if test "$1" = 5; then
shift
goto label "$@"
fi
Seriously, don't do this.