用于在给定目录

时间:2018-06-01 08:33:05

标签: bash shell unix

我编写了以下shell脚本来在每个包的目录中执行给定的命令集。如果任何命令失败,它应该停止。它还应该在控制台上显示命令输出。

选项

需要3个参数
  1. ' -b'包的基本目录
  2. ' -c'逗号分隔的命令列表
  3. ' -p'逗号分隔的包列表(个人 目录)
  4. Shell脚本

    #!/bin/bash
    
    #Function to execute a command
    executeCommand(){
      printf "\n**** Executing Command: '$1' *****\n\n"
      $1
      return $?
    }
    
    
      #Initialize the variables with command line arguments
      while getopts "c:p:b:" options; do
        case $options in
            b ) set -f # disable glob
                IFS=, # split on space characters
                base_directory=$OPTARG ;; # use the split+glob operator    
            c ) set -f # disable glob
                IFS=, # split on space characters
                commands=($OPTARG) ;; # use the split+glob operator
            p ) set -f # disable glob
                IFS=, # split on space characters
                packages=($OPTARG) ;; # use the split+glob operator    
        esac
      done
    
      #Iterate over all packages
      for (( i = 0; i < ${#packages[@]} ; i++ )); do
    
        #Go to each package directory
        if executeCommand "cd ${base_directory}${packages[$i]}"; then
    
          #Execute all the commands one by one for current package
          for (( j = 0; j < ${#commands[@]} ; j++ )); do
            if executeCommand "${commands[$j]}"; then
              echo "Successfully Executed the Command"
            else
              break 2;
            fi  
          done
        else
          break;
        fi 
      done  
    

    如果我使用以下参数执行它,它会给我一个错误没有这样的文件或目录但是,如果我手动执行cd /local/workplace/directory1它会转到directory1

    执行和错误

    ~/bb-slds.sh \
        -c "build clean","build package"  \
        -p directory1,directory1 \
        -b /local/workplace/
    
    **** Executing Command: 'cd /local/workplace/directory1' *****
    
    /home/jramay/bb-slds.sh: line 6: cd /local/workplace/directory1: No such file or directory
    

    如果我不使用getopts并将变量初始化如下,那么它可以正常工作。

    base_directory="/local/workplace/"
    
    declare -a commands=(
      "build clean"
      "build package"  
      )
    
    declare -a packages=(
      "directory1"
      "directory2"
      )
    

1 个答案:

答案 0 :(得分:1)

这是一个棘手的问题。 :)

您在IFS循环期间更改了getopts,并且从未将其更改回旧值。所以当你写:

$1

executeCommand中,它不会将空格视为cd与其参数之间的分隔符。

完成getopts后,您需要将其设置回默认值:

IFS=$' \t\n'

set -f之后,getopts更改仍然存在。你应该在循环之前做一次,然后放

set +f

之后。