在 Unix 外壳脚本中设置退出代码



我有 test.sh 它有多个返回条件 test1.sh 只是回显语句。当我运行 test2.sh 我的逻辑应该运行 test.sh 处理文件,即"成功文件"并调用 test1.sh 脚本。当执行其他条件时,它不应运行 test1.sh 脚本,即"文件未成功","目录中不存在输入文件"

我面临的问题是,当它执行其他条件时,例如"文件未成功","目录中不存在输入文件",它不会重新调整"1"作为指定的退出代码,而是反过来返回0,即从操作系统表示作业成功。所以我在所有不同条件下都从 test.sh 得到"0",所以无论文件处理是否失败等,都会调用 test1 .sh。请告知返回代码

test.sh
FILES=/export/home/input.txt
cat $FILES | nawk -F '|' '{print $1 "|" $2 "|" }' $f > output.unl
if [[ -f $FILES ]]; 
then if [[ $? -eq 0 ]]; then
 echo "File successfully" 
else
 echo "File not successfully"
 exit 1 
fi
 else 
echo "Input file doesn't exists in directory" exit 1 fi

====

============================================================================
test1.sh
 echo "Input file exists in directory"

test2.sh
echo "In test2 script"
./test.sh
echo "return code" $?
if [[ $? -eq  0 ]]; then
 echo "inside"
./test1.sh
fi

当你在 echo 中使用它时,你会覆盖$? - 之后,它包含 echo 本身的退出代码。将其存储在变量中以避免这种情况。

echo "In test2 script"
./test.sh
testresult=$?
echo "return code" $testresult
if [[ $testresult -eq  0 ]]; then
  echo "inside"
  ./test1.sh
fi

编辑添加:很难从 test.sh 中分辨出您想要什么,因为您粘贴的代码不完整,甚至无法运行。看起来你的意思是catif内,否则当输入文件丢失时它会出错,并且您的$?测试什么也不做。所以我像这样重新排列它:

FILES=input.txt
if [[ -f $FILES ]]; then
  cat $FILES | awk -F '|' '/bad/{ exit 1 }'
  if [[ $? -eq 0 ]]; then
    echo "File processed successfully"
  else
    echo "File processing failed"
    exit 1
  fi
else
  echo "Input file doesn't exist in directory"
  exit 1
fi

我已经更改了awk脚本以演示所有工作条件:现在,如果我在输入中输入单词bad.txt您将看到"文件处理失败"消息,否则您将看到成功;删除文件,您将看到输入文件不存在消息。

最新更新