如何测试命令的输出是否为空或空字符串?

如何测试命令的输出是否为空或空字符串?

我正在尝试获取一个预提交挂钩脚本来在我们的旧 SVN 盒子上工作。它非常旧,运行 Ubuntu Server 8.04。

此脚本: @echo off :: :: 停止具有空日志消息的提交。 ::

@echo off

setlocal

rem Subversion sends through the path to the repository and transaction id
set REPOS=%1
set TXN=%2

rem check for an empty log message
svnlook log %REPOS% -t %TXN% | findstr . > nul
if %errorlevel% gtr 0 (goto err) else exit 0

:err
echo. 1>&2
echo Your commit has been blocked because you didn't give any log message 1>&2
echo Please write a log message describing the purpose of your changes and 1>&2
echo then try committing again. -- Thank you 1>&2
exit 1

我认为它不起作用,因为命令 findstr 不存在。起作用的是这样的:

if [[ -n "" ]] ; then echo "yes"; else echo "no"; fi

所以我将脚本更改为:

@echo off
::
:: Stops commits that have empty log messages.
::

@echo off

setlocal

rem Subversion sends through the path to the repository and transaction id
set REPOS=%1
set TXN=%2

rem check for an empty log message
::svnlook log %REPOS% -t %TXN% | findstr . > nul
::if %errorlevel% gtr 0 (goto err) else (goto exitgood)

::svnlook log %REPOS% -t %TXN% | findstr . > ""
::if %errorlevel% gtr 0 (goto err) else (goto exitgood)

SET LOG=`svnlook log %REPOS% -t %TXN%`

if [[ -n %LOG%  ]]; then
        (goto exitgood)
else
        (goto err)
fi

:err
echo. 1>&2
echo Your commit has been blocked because you didn't give any log message 1>&2
echo Please write a log message describing the purpose of your changes and 1>&2
echo then try committing again. -- Thank you 1>&2
exit 1

:exitgood
exit 0

但这也不起作用,它们都以代码 255 退出。有人可以告诉我我做错了什么吗?

答案1

这些是批处理脚本 – 就像 MS Windows Batch 中一样。 查找字符串是在 Windows NT 4 资源工具包中引入的。

::rem是评论。 (或者::实际上是一个带有无效的姓名)。

您可能可以在 下运行它们wine cmd,但最好将它们移植到某些本机脚本(perl、python、bash 等)。

简单的例子:

#!/bin/bash

# Function to print usage and exit
usage()
{
    printf "Usage: %s [repository] [transaction_id]\n" $(basename "$1") >&2
    exit 1
}

# Check that we have at least 2 arguments
[ $# -ge 2 ] || usage

repo="$2"
trans_id="$2"

# Check that command succeed, and set variable "msg" to output
if ! msg="$(svnlook log "$repo" -t "$trans_id")"; then
    printf "Check path and id.\n" >&2
    usage
fi

# If msg is empty
if [ "$msg" = "" ]; then
    printf \
"Your commit has been blocked because you didn't give any log message
Please write a log message describing the purpose of your changes and
then try committing again. -- Thank you.\n" >&2
     exit 2    
fi

# Else default exit AKA 0

相关内容