linux - shell脚本中"if[ 0 -lt 1] command not found"错误

标签 linux shell unix

我收到错误消息 if[ 0 -lt 1]找不到命令。我刚刚开始编写 shell 脚本。我不知道我的代码有什么问题:

if[ $# -lt  1 ]   
then
  echo "Give a number as a parameter. Try again."        
else        
  n=$1    
  sum= 0  
  sd=0    
  while[ $n -gt 0 ]                                     
  do     
    sd=`expr $n % 10`                                  
    sum=`expr $sum + $sd`                               
    n=`expr $n / 10`                                    
  done    
  echo "Sum of digits for $1 is $sum"

最佳答案

if[ 之间需要有一个空格。 while 之后您会遇到同样的问题。

[ ] 符号在 shell 中有点奇怪。它看起来像是语言的一部分,但实际上不是。 ifwhile 单词后面始终需要跟有空格,然后是一个命令,该命令将被执行,并根据其退出代码是零还是非零来判断是真还是假。

所以实际上有一个名为 [ 的命令,它评估命令行上给出的条件,并根据条件评估为 true 或 false 以退出代码终止。在大多数系统上,您可以在 /usr/bin 目录中看到可执行文件(尽管 shell 通常有一个内置版本以提高效率)。它的工作原理与测试相同。

此外,请记住,if 需要在 else 子句之后匹配 fi

关于linux - shell脚本中"if[ 0 -lt 1] command not found"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47113413/

相关文章:

linux - 暂停远程主机中的进程并在另一台远程主机中恢复执行

c - C语言中fgets函数的使用

c - 信号量并发

perl - 找到: missing argument to `-exec' in perl script

shell - 通过SSH执行大量命令

linux - 如何验证两个 zip 包之间的等效性

unix - grep 一些文件

xml - 如何从 ec2 实例中的用户数据编辑 xml 行?

linux - 两个具有相同路径权限的 FTP 用户

Python Tkinter : Attach scrollbar to listbox as opposed to window