即使命令不起作用,如何处理所有错误消息?

时间:2019-06-09 23:21:42

标签: linux bash

我对bash shell脚本有点不满意。我创建了以下脚本:

#!/bin/bash

display_usage() {
        echo -e "\nUsage: This script must be run with both a valid source and a target client name."
        echo -e "Example: ./createClientRolesRespChart <source client name> <target client name>\n"
        }

mv $1 $2

# If less than two arguments supplied, display usage
if [  $# -le 1 ]; then
        display_usage
        exit 1
fi

if [ $? -eq 0 ]; then
   echo "Created new response chart for the $2 client."
   exit 0
else
    echo "[Error] Move (mv) command failed. Please check parameters are correct."
    exit 1
fi

该脚本有效,但是如果我输入了错误的文件名,该命令将失败,购买后仍会打印成功消息。任何提示。应该是一件容易的事。我只是忘记了:(

bash-3.2$ ./createClientRolesRespChart foo bar
mv: rename foo to bar: No such file or directory
Created new response chart for the bar client.

1 个答案:

答案 0 :(得分:3)

$?仅表示上一条命令是否成功。在您的情况下,您正在执行mv,但失败了,然后查看了参数计数,然后查看了$?,现在它将包含参数计数检查的结果,而不是mv。要解决此问题,请切换参数计数检查和mv