linux - 简化 bash 代码

标签 linux bash shell

<分区>

我在 shell 脚本中有以下代码。一切正常。

#!/bin/bash

baseDirPath = '/stackoverflow/question'
newDir = '/stackoverflow/question/answers'


# first check some business condition
if [[ some condition here ]]
then
     # check if base Directory path already exit 
     if [ -d  $baseDirPath ];then

        # check if new Directory exits or not, if not create one 
        if [ ! -d $newDir ];then

          mkdir $newDir
          if [ $? -ne 0 ] ; then
            echo "error occurred while creating directory "
          fi
        fi
     else
       exit 1;
     fi
fi

我觉得这是非常困惑且不是很干净的代码。 我对编程很陌生,所以不确定它如何干净。

我很好奇它是否可以变得更简单或者有其他方法可以做到这一点。

(上面没有展示完整的shell脚本,只展示了复杂的if-else部分。)

最佳答案

#!/bin/bash

die(){ >&2 printf '%s\n' "$@"; exit 1; }

#Can't have spaces here
baseDirPath='/stackoverflow/question' 
newDir='/stackoverflow/question/answers'


# first check some business condition
if [ some condition here ]; then
     # check if base Directory path already exit 
   mkdir -p "$newDir" ||  die 'error occured while creating directory'
fi

这会稍微改变语义——如果 newDirs 的创建由于任何原因失败,它会退出——baseDirPath 不是目录或 baseDirPath 是一个目录,无法创建 newDir

您也可以删除该错误消息。 mkdir 如果由于某种原因失败,它已经在 stderr 上给你一个错误:

mkdir -p "$newDir" || exit 1

如果你的大部分命令都应该像这样工作(即要么成功要么关闭整个脚本),那么你最好设置 set -e(~ 在命令返回时退出具有非零状态)然后只是做:

mkdir -p "$newDir"

关于linux - 简化 bash 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33699153/

相关文章:

java - 如何在 mono/linux 上从 Java 调用 .Net dll(函数)

linux - 源树差异摘要信息

arrays - 在给定索引处添加一个值而不删除

linux - 关于使用 bash/sed/awk 脚本重新排序网络路由文件的方法的思考

bash - 删除 netstat 输出(特别是 Not all processes could be identify 行)

linux - 表达式为字符串(shell 脚本)

sql - 在 Linux 上的 Qt 中连接到 SQL SERVER

linux - 命令替换、bash 和管道出错

正则表达式 egrep 找到 .gz 但不是 .tar.gz

linux - 用于监视日志文件的 Shell 脚本,如果关键字触发则运行 snmptrap 命令