bash if 语句在 crontab 作业中出现意外行为

Nab*_*ham 4 linux shell bash cron conditional

这是脚本

bash --version | head -n1
if [ "$1" == "now"  ]
then
    echo if now
    execut job
else
    echo else "_"$1"_"  # make sure we are not picking any spaces
    if [ condition  ]
    then
    execut something else
    fi
fi

./script now
if now
Run Code Online (Sandbox Code Playgroud)

如果从交互式 shell 运行,则按预期工作。但是,如果从 cron as 调用,则 if 会转到 else 块

* * * * *   root    /home/user/./script now >> /tmp/log
cat /tmp/log
GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)
else _now_
Run Code Online (Sandbox Code Playgroud)

也与“-eq”相同。

我是否因为没有吃早餐而错过了一些非常简单的事情?

运行 Ubuntu 14.04LTS。

Fro*_*giz 6

因为语法只有一个相等: [ $a = $b ]

 if [ ! $a = $b ]; then     #with space in condition and need instruction between then and fi, else doesn't works
 ...Script to execute...
 elif [ ! $a = $c ]; then
 ...Script to execute...
 else
 ...Script to execute...
 fi     
Run Code Online (Sandbox Code Playgroud)

条件sh列表

 [ $a = $b ] && return 1 || return 0        conditionnal alternative format
 if [ $a = $b -o $b = $c ]          -o mean OR
 if [ $a = $b -a $b = $c ]          -a mean AND
 if [ $a = $b -o $b = $c ] || [ $a = $b -a $a = $c ] multiple conditionnal or
 if [ $a = $b -o $b = $c ] && [ $a = $b -a $a = $c ] multiple conditionnal and
 if [ -z $a ]                       is empty or null
 if [ ! -z $a ]                     not equal to ""
 if [ -n $a ]                       is not empty or null
 if [ $a -eq $b ]                   equal (numeric)
 if [ $a -ne $b ]                   not equal (numeric)
 if [ $a -gt $b ]                   greater than (numeric)
 if [ $a -ge $b ]                   greater or equal than (numeric)
 if [ $a -lt $b ]                   lower than (numeric)
 if [ $a -le $b ]                   lower or equal than (numeric)
 if [ -d $a ]                       is a directory  
 if [ -e $a ]                       file exist  
 if [ -f $a ]                       is a file
 if [ -g $a ]                       is group allowed for the file
 if [ -r $a ]                       is readable 
 if [ -s $a ]                       file is not 0kb
 if [ -u $a ]                       is user allowed for file
 if [ -w $a ]                       is writable
 if [ -x $a ]                       is executable
Run Code Online (Sandbox Code Playgroud)

更多与 bash

 if [[ "$a" =~ "$b" ]]              match (reg exp)
 if [[ $a == *$b* ]]                match (glob)
 if [ "${a/$b}" = $a ]              match (string)
 if [ -z "${a##*$b*}" ]             match (string, work with dropbox !)
 if [ ${a/$b} = $a ]                match (string)
Run Code Online (Sandbox Code Playgroud)

  • 对此进行扩展: bash 允许`==`,但所有其他 shell 不允许。由于这个脚本不以shebang 行(例如`#!/bin/bash`)开始,它在哪个shell 下运行取决于任何启动它的心血来潮。当您从交互式 bash shell 运行它时,它使用 bash。当 cron 运行它时,它默认为 /bin/sh,它在你的系统上实际上是 `dash` —— 一个更基本的 shell,不支持 `==` 或 `[[ ]]` 或任​​何其他 bash 扩展. 顺便说一句,不要为此使用`-eq`——它进行数字比较,而不是字符串比较。 (3认同)