Quando mudei do Windows para o Linux na minha área de trabalho, eu tinha muitos arquivos .BAT
e .CMD
pré-existentes para converter e eu não ia reescrever a lógica para eles, então eu encontrado uma maneira de fazer um goto no bash que funciona porque a função goto executa sed
em si mesma para remover todas as partes do script que não devem ser executadas e, em seguida, avaliar tudo:
#!/bin/bash
# BAT / CMD goto function
function goto
{
label=$1
cmd=$(sed -n "/^:[[:blank:]][[:blank:]]*${label}/{:a;n;p;ba};" $0 |
grep -v ':$')
eval "$cmd"
exit
}
apt update
# Just for the heck of it: how to create a variable where to jump to:
start=${1:-"start"}
goto "$start"
: start
goto_msg="Starting..."
echo $goto_msg
# Just jump to the label:
goto "continue"
: skipped
goto_msg="This is skipped!"
echo $goto_msg
: continue
goto_msg="Ended..."
echo "$goto_msg"
# following doesn't jump to apt update whereas original does
goto update
e eu não me sinto culpado como Linus Torvalds disse de maneira famosa:
From: Linus Torvalds
Subject: Re: any chance of 2.6.0-test*?
Date: Sun, 12 Jan 2003 11:38:35 -0800 (PST)
I think goto's are fine, and they are often more readable than large amounts of indentation. That's especially true if the code flow isn't actually naturally indented (in this case it is, so I don't think using goto is in any way clearer than not, but in general goto's can be quite good for readability).
Of course, in stupid languages like Pascal, where labels cannot be descriptive, goto's can be bad. But that's not the fault of the goto, that's the braindamage of the language designer.
Fonte para código (modificada para torná-la menos propensa a erros)
< a href="http://koblents.com/Ches/Links/Month-Mar-2013/20-Using-Goto-in-Linux-Kernel-Code/"> Fonte para cotação