为什么我的 bash 脚本会打印出意外的结果?
Why does my bash script print an unexpected result?
我有一个简单的 bash 脚本如下:
#!/bin/bash
n=$(( RANDOM % 100 ))
if [[ n -eq 42 ]]; then
echo "Something went wrong"
>&2 echo "The error was using magic numbers"
exit 1 fi
echo "Everything went according to plan"
但是,当我 运行 通过在 bash 中键入以下代码时:
sh script.sh
我得到以下输出:
script.sh: 5: [[: not found
Everything went according to plan
为什么会打印script.sh: 5: [[: not found
?我知道我错过了第 2 行的内容,但我不知道是什么。
bash和sh不一样shell,所以语法也不一样相似
你想要的 sh
if [ $n -eq 42 ]; then echo "Something went wrong" >&2 ;echo "The error was using magic numbers" ; exit 1 ;fi
所以在 'n' 之前没有双重 '[' ']' 和 '$' 并添加了缺失的 ';'
另请注意,您的代码对于 bash 也是错误的,因为缺少 ';',您需要 :
if [[ n -eq 42 ]]; then echo "Something went wrong" >&2;echo "The error was using magic numbers" ; exit 1 ;fi
我有一个简单的 bash 脚本如下:
#!/bin/bash
n=$(( RANDOM % 100 ))
if [[ n -eq 42 ]]; then
echo "Something went wrong"
>&2 echo "The error was using magic numbers"
exit 1 fi
echo "Everything went according to plan"
但是,当我 运行 通过在 bash 中键入以下代码时:
sh script.sh
我得到以下输出:
script.sh: 5: [[: not found
Everything went according to plan
为什么会打印script.sh: 5: [[: not found
?我知道我错过了第 2 行的内容,但我不知道是什么。
bash和sh不一样shell,所以语法也不一样相似
你想要的 sh
if [ $n -eq 42 ]; then echo "Something went wrong" >&2 ;echo "The error was using magic numbers" ; exit 1 ;fi
所以在 'n' 之前没有双重 '[' ']' 和 '$' 并添加了缺失的 ';'
另请注意,您的代码对于 bash 也是错误的,因为缺少 ';',您需要 :
if [[ n -eq 42 ]]; then echo "Something went wrong" >&2;echo "The error was using magic numbers" ; exit 1 ;fi