не замеченной. Реализация функции goto, как заявлено для dash, bash и ksh. Проверяла только
на bash в linux и ksh93 во freebsd.
Код: Выделить всё
#!/usr/local/bin/dash
# goto_demo.sh
# goto ': some_label:'
goto()
{
line_number=1
start_line=1
while IFS='' read -r line
do
if [ "${line}" = "${1}" ]
then
: > /tmp/goto.tmp
start_line=${line_number}
fi
if [ ${line_number} -ge ${start_line} ]
then
echo "${line}" >> /tmp/goto.tmp
fi
line_number=$(( line_number + 1 ))
done
. /tmp/goto.tmp
} < ${0}
goto ': second:'
echo 'This will not be printed!'
: first:
echo '**************************************'
echo 'You are at first label!'
# cat /tmp/goto.tmp
echo '**************************************'
goto ': third:'
echo 'This will not be printed either!'
: second:
echo '**************************************'
echo 'You are at the second label!'
# cat /tmp/goto.tmp
echo '**************************************'
goto ': first:'
echo 'And finally, this will not be printed either!'
: third:
echo '**************************************'
echo 'You are at the third label!'
echo '######## cat /tmp/goto.tmp... ########'
cat /tmp/goto.tmp
echo '###### END cat /tmp/goto.tmp... ######'
echo '**************************************'
: end:
echo 'Exiting...'
echo '**************************************'
exit
Код: Выделить всё
./goto_demo.sh
**************************************
You are at the second label!
**************************************
**************************************
You are at first label!
**************************************
**************************************
You are at the third label!
######## cat /tmp/goto.tmp... ########
: third:
echo '**************************************'
echo 'You are at the third label!'
echo '######## cat /tmp/goto.tmp... ########'
cat /tmp/goto.tmp
echo '###### END cat /tmp/goto.tmp... ######'
echo '**************************************'
: end:
echo 'Exiting...'
echo '**************************************'
exit
###### END cat /tmp/goto.tmp... ######
**************************************
Exiting...
**************************************
Код: Выделить всё
goto()
{
line_copy=
while IFS='' read -r line
do
[ "$line" = "$1" ] && line_copy=1
[ -n "$line_copy" ] && echo "$line"
done < "$0" > /tmp/goto.tmp
. /tmp/goto.tmp
}
Конечно с временным файлом хак выглядит довольно органично но может варианты
через переменные или неименованный канал будут не на много сложнее? В любом
случае это интересно.