繁体   English   中英

如何跳回 bash 脚本中的行?

[英]how to jump back to line in bash script?

我有“if”循环,并希望在我的“then”部分中,命令将是“跳回行......并从该行全部运行脚本”。 我该怎么写

if [ -s file.txt ] 
then
    jump to command \ jump to line ....
else 
    <command> 
fi 

谢谢

如何避免goto并从某个点开始处理? 例如,您希望重新开始处理,直到标志的值为 5。
评论提到了一个loop 脏循环是这样的:

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

在你想“好吧,这就是我想要的 goto。你在 bash 中需要多少开销”之前,看看第二个实现。

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"

这已经看起来更好了。 当 function 很小时,你可以把所有东西都放在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"

这个例子你可以使用不同的loop 在为每个步骤编写语句之前,请查看结构并考虑您需要哪些控制功能。 也许你想要一个简单的

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"

当您的loop的行数多于屏幕时,请考虑使用 function 来获取小细节。

(注意:这是一个糟糕的主意)

shell 没有给你一个 goto,但你可以制造一个!

#!/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

说真的,不要这样做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM