bash中是否有“goto”语句?我知道这被认为是不好的做法,但我需要特别“去”。


当前回答

一个简单的可搜索的goto,用于在调试时注释掉代码块。

GOTO=false
if ${GOTO}; then
    echo "GOTO failed"
    ...
fi # End of GOTO
echo "GOTO done"

结果是-> GOTO done

其他回答

它确实可能对一些调试或演示需求有用。

我发现Bob Copeland解决方案http://bobcopeland.com/blog/2012/10/goto-in-bash/优雅:

#!/bin/bash
# include this boilerplate
function jumpto
{
    label=$1
    cmd=$(sed -n "/$label:/{:a;n;p;ba};" $0 | grep -v ':$')
    eval "$cmd"
    exit
}

start=${1:-"start"}

jumpto $start

start:
# your script goes here...
x=100
jumpto foo

mid:
x=101
echo "This is not printed!"

foo:
x=${x:-10}
echo x is $x

结果:

$ ./test.sh
x is 100
$ ./test.sh foo
x is 10
$ ./test.sh mid
This is not printed!
x is 101

我找到了一种使用函数的方法。

例如,您有3个选择:A、B和C。A和Bexecute一个命令,但是C给您更多信息,并再次将您带到原始提示符。这可以使用函数来完成。

请注意,由于包含demoFunction函数的那一行只是设置了函数,因此需要在脚本之后调用demoFunction,以便函数能够实际运行。

您可以通过编写多个其他函数并在需要“GOTO”shell脚本中的其他位置时调用它们来轻松地适应这一点。

function demoFunction {
        read -n1 -p "Pick a letter to run a command [A, B, or C for more info] " runCommand

        case $runCommand in
            a|A) printf "\n\tpwd being executed...\n" && pwd;;
            b|B) printf "\n\tls being executed...\n" && ls;;
            c|C) printf "\n\toption A runs pwd, option B runs ls\n" && demoFunction;;
        esac
}

demoFunction

不,没有;关于存在的控制结构的信息,请参见Bash参考手册中的§3.2.4“复合命令”。特别要注意的是,Bash中提到了break和continue,它们不像goto那样灵活,但在Bash中比在某些语言中更灵活,可能会帮助您实现想要的结果。(无论你想要什么……)

对于创建类似“goto”的东西,我的想法是使用带大小写的select并赋值一个变量,然后在if语句中检查该变量。不完美,但在某些情况下可能有帮助

例子:

#!/usr/bin/env bash

select goto in Ubuntu Debian Quit ; do
    case $goto in
        Ubuntu) { CHOICE="Ubuntu" ; break ; } ;;
        Debian) { CHOICE="Debian" ; break ; } ;;
        Quit)   { echo "Bye" ; exit ; } ;;
        *)      { echo "Invalid selection, please try again..." ; } ;;
    esac
done

if [ "$CHOICE" == "Ubuntu" ]; then
    echo "I'm in Ubuntu"
fi

if [ "$CHOICE" == "Debian" ]; then
    echo "I'm in Debian"
fi

为什么没有人直接使用函数呢? 顺便说一句,处理函数比制作新东西容易得多

我的风格:

#!/bin/bash

# Your functions
function1 ()
{
    commands
}

function2 ()
{
    commands
}
    :
    :

functionn ()
{
    commands
}

# Execute 1 to n in order
for i in {1..n}
    do
        function$i
    done

# with conditions
for i in {1..n}
    do
        [ condition$i ] && function$i
    done

# Random order
function1
functionn
function5
    :
    :
function3

以上风格的例子:

#!/bin/bash

# Your functions
function1 ()
{
    echo "Task 1"
}

function2 ()
{
    echo "Task 2"
}

function3 ()
{
    echo "Task 3"
}

function1
function3
function2

输出:

Task 1
Task 3
Task 2

缺点:

有组织地编写脚本。 问题少,不容易出错。 你可以在已有的函数中创建函数。 来回移动没有任何问题。