Shell代码没有响应while,loop,date

时间:2014-04-18 01:07:58

标签: bash shell

我评论了我的while循环以测试它,但是我的shell脚本有些问题。

name = ""
while [test -z name]; do
echo "Please enter your name:"
read name
done
echo "Hello $name"
echo $date
hour = $(date +H)
if test $hour -ge 9
then
echo "Welcome you are on time again!"
else
echo "You are running behind your scheduled time!"
echo "Employees must be logged in by 9 am."
echo "$name arrived late on $date" >> checkin
fi

未注释while时,它不会进入循环。我认为这与我的条件有关。它也没有正确输入if语句。我不确定这是什么样的正确格式。

输出如下:

project2: line 1: name: command not found
project2: line 2: [test: command not found
Hello 

project2: line 8: hour: command not found
project2: line 9: [test: command not found
You are running behind your scheduled time!
Employees must be logged in by 9 am.

Edit2:不知道这是否合法,但在这里:

while循环已修复,谢谢你们。知道我的if声明发生了什么吗?

新代码:

name = ""
while test -z "$name"
do
   echo "Please enter your name:"
   read name
done
echo "Hello $name"
echo $date
hour = $(date +H)
if test "$hour" -ge "9"
then
  echo "Welcome you are on time again!"
else
  echo "You are running behind your scheduled time!"
  echo "Employees must be logged in by 9 am."
  echo "$name arrived late on $date" >> checkin
fi

输出

Please enter your name:

Please enter your name:

Please enter your name:
Jack
Hello Jack

project2: line 9: hour: command not found
project2: line 10: test: : integer expression expected
You are running behind your scheduled time!
Employees must be logged in by 9 am.

根据代码和输入,“请输入您的姓名”重复是正确的。知道if声明发生了什么吗?这是bash shell,我可能应该提到。

2 个答案:

答案 0 :(得分:2)

以下是修订后的代码版本,可充分利用bash功能 - 所有更改都标有注释:

  # NO spaces allowed around `=` in ASSIGNMENTS.
  # Note: By contrast, when `=` or `==` are used 
  #       in CONDITIONALS for COMPARISON, you MUST have spaces around them.
name=""
  # Use `[[ ... ]]` rather than `[ ... ]` or `test` in bash":
  # It's more robust (mostly no need for quoting) and
  # has more features.
  # You MUST have a space after `[[` and before `]]` (same goes for `[` and `]`).
while [[ -z $name ]]
do
   echo "Please enter your name:"
   read name
done
echo "Hello, $name"
  # There is no `$date` variable. But you can use 
  # COMMAND SUBSTITUTION - `$(...)` to capture the
  # `date` utility's output:
dateNow=$(date)
  # NO spaces around `=`; `H` must be prefixed with `%`
  # to return the hour (thanks, @alvits).
hour=$(date +%H)
  # Use ARITHMETIC EVALUATION - `(( ... ))`
  # for numerical comparisons.
  # You can refer to variables without the $ prefix,
  # and use C-style arithmetic expressions.
if (( hour > 9 ))
then
  echo "Welcome, you are on time again!"
else
  echo "You are running behind your scheduled time!"
  echo "Employees must be logged in by 9 am."
  echo "$name arrived late on $dateNow" >> checkin
fi

答案 1 :(得分:2)

变量分配不应包含=周围的空格。

使用[...]的语句必须在封闭括号前的空格和空格后有空格。

变量必须以$为前缀。 while [ -z "$name" ]应足以测试名称是否为空。

您应该从hour=$(date +H)更改为hour=$(date +%H)以实际指定小时值而不是字母H

echo $date指的是名为date的变量。但是,您没有名为date的变量,因此它将打印为空。