linux - 第一个 Bash 文件中的错误

标签 linux ksh

我正在编写我的第一个 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>

如有任何帮助,我们将不胜感激!

最佳答案

首先有几件事:

  1. 如果尝试使用 bash 脚本,shebang 应该是#!/bin/bash。 (如果已经使用 bash,则不需要,通过在终端中打印 $SHELL 进行检查)
  2. if(以及 while)条件应适当间隔。例如。如果/空间/[/空间/条件/空间/]
  3. 正如评论中所述,在赋值时不要使用 $。
  4. $# 表示命令行参数的数量。

其余的你可以从更正后的代码中理解:

#!/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

关于linux - 第一个 Bash 文件中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54585137/

相关文章:

c - 如何在 Ubuntu 10.04 (lucid) 上安装 xlibs-dev?

linux查找文件并创建硬链接(hard link)

ksh - 如果超出 ksh 中的字符串限制,则附加空格或截断字符串

shell - ls 命令 KornShell

shell - KornShell (ksh) 是否有 Do...While 循环?

linux - SQUID启用离线模式使用缓存加载网页

linux - 在 Linux 终端中运行文件

java - 如何使用 java 或 shell 脚本查找 unix/linux 系统信息?

hadoop - HBase start-hbase.sh在第二个节点上失败

ksh - 将 ksh 输入数组存储到变量并传递给另一个脚本