linux - 第一个 Bash 文件中的错误
问题描述
我正在编写我的第一个 bash 脚本,但我不断收到错误,我不确定我哪里出错了。下面是我试图执行的脚本:
#!/bin/ksh
#Script Name: printnum.sh
# Verify the number of arguments and exit if not equal to 1`enter code here`
$mynum = "5"
echo $mynum
if [$mynum -gt 1]
then
printf "error: program must be executed with 1 argument\n"
printf "usage: $0 value (where value >= 1)\n"
exit 1
fi
# Verify argument is a positive number
if [$mynum -lt 1]
then
printf "error: argument must be a positive number\n"
printf "usage: $0 value (where value >= 1)\n"
fi
# Store command line argument in variable i
$mynum="$i"
# Loop and print $i while decrementing variable to =1 (with comma)
while [$i -gt 1]
do
printf "$i, "
done
以下是我得到的错误:
./printnum.sh[3]: =: not found [No such file or directory]
./printnum.sh[5]: [: ']' missing
./printnum.sh[11]: [: ']' missing
./printnum.sh[16]: =: not found [No such file or directory]`enter code here`
./printnum.sh[17]: [: ']' missing
/export/home/hanko01/HOME/itec400/homework>
这里的任何帮助将不胜感激!
解决方案
先说几点:
- 如果尝试使用 bash 脚本,shebang 应该是 #!/bin/bash。(如果已经使用 bash,则不需要,通过在终端中打印 $SHELL 进行检查)
- if(以及 while)条件应适当间隔。例如。如果/空格/[/空格/条件/空格/]
- 正如评论中所说,在赋值时不要使用 $ 。
- $# 用于命令行参数的数量。
其余的你可以从更正后的代码中理解:
#!/bin/bash
#Script Name: printnum.sh
# Verify the number of arguments and exit if not equal to 1 `enter code here`
if [ $# -ne 1 ]
then
printf "error: program must be executed with 1 argument\n"
printf "usage: $0 value (where value >= 1)\n"
exit 1
fi
# Verify argument is a positive number
if [ $1 -lt 1 ]
then
printf "error: argument must be a positive number\n"
printf "usage: $0 value (where value >= 1)\n"
fi
# Store command line argument in variable i
i=$1
# Loop and print $i while decrementing variable to =1 (with comma)
while [ $i -gt 1 ]
do
printf "$i, "
i=$((i-1))
done
推荐阅读
- javascript - 无法使用 Barba.js 和机车滚动向下滚动
- asp.net-mvc - Scaffold-DbContext 没有在 Generated 类上添加 [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
- json - 如何在 JMeter 5.3 中验证整个 JSON 响应?
- javascript - 为什么我的 Firestore 分页查询不起作用?
- python - Python 库 - 如何在库外更新我的库的版本?
- ruby-on-rails - 为什么在 RubyXL 中开发的超链接在 LibreOffice 而不是 Excel 中工作
- ios - Google Places Api,未按预期找到结果,需要城市下的区域名称
- php - 使用 Laravel Eloquent ORM 连接另外四个表
- c++ - Qt中的整数用户输入
- javascript - Angular 组件不会刷新 UI