Güvenli tarafta olmak için, bash bir sözdizimi hatasıyla karşılaşırsa bir komut dosyasının yürütülmesini iptal etmek istiyorum.
Şaşırtıcı şekilde, bunu başaramıyorum. ( set -eyeterli değildir.) Örnek:
#!/bin/bash
# Do exit on any error:
set -e
readonly a=(1 2)
# A syntax error is here:
if (( "${a[#]}" == 2 )); then
echo ok
else
echo not ok
fi
echo status $?
echo 'Bad: has not aborted execution on syntax error!'
Sonuç (bash-3.2.39 veya bash-3.2.51):
$ ./sh-on-syntax-err
./sh-on-syntax-err: line 10: #: syntax error: operand expected (error token is "#")
status 1
Bad: has not aborted execution on syntax error!
$
$?Sözdizimi hatalarını yakalamak için her ifadeden sonra kontrol edemeyiz .
(Makul bir programlama dilinden böyle güvenli bir davranış bekliyordum ... belki de bu geliştiriciler için bir hata / dilek olarak rapor edilmelidir)
Daha fazla deney
if fark etmez.
Çıkarma if:
#!/bin/bash
set -e # exit on any error
readonly a=(1 2)
# A syntax error is here:
(( "${a[#]}" == 2 ))
echo status $?
echo 'Bad: has not aborted execution on syntax error!'
Sonuç:
$ ./sh-on-syntax-err
./sh-on-syntax-err: line 6: #: syntax error: operand expected (error token is "#")
status 1
Bad: has not aborted execution on syntax error!
$
Belki de http://mywiki.wooledge.org/BashFAQ/105'teki egzersiz 2 ile ilgilidir ve bununla bir ilgisi vardır (( )). Ancak, bir sözdizimi hatası yürütmeye devam etmenin hala mantıksız olduğunu düşünüyorum.
Hayır, (( ))fark etmez!
Aritmetik test olmadan bile kötü davranır! Basit, basit bir script:
#!/bin/bash
set -e # exit on any error
readonly a=(1 2)
# A syntax error is here:
echo "${a[#]}"
echo status $?
echo 'Bad: has not aborted execution on syntax error!'
Sonuç:
$ ./sh-on-syntax-err
./sh-on-syntax-err: line 6: #: syntax error: operand expected (error token is "#")
status 1
Bad: has not aborted execution on syntax error!
$
set -eişe yaramadı bir açıklama olabilir . Ama sorum hala mantıklı. Herhangi bir sözdizimi hatası iptal edilebilir mi?
set -esözdizimi hatasının birififadede olduğu için yeterli değil . Başka herhangi bir yer betiği iptal etmelidir.