Shell脚本在给定目录中执行命令集

贾法尔·拉玛(Jaffar Ramay)

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

它需要3个带有选项的参数

  1. 软件包的“ -b”基本目录
  2. “ -c”逗号分隔的命令列表
  3. “ -p”逗号分隔的软件包列表(各个目录)

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"
  )
巴尔玛

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

IFSgetopts循环中进行了更改,但从未将其更改回旧值。所以当你写:

$1

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

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

IFS=$' \t\n'

set -f之后的变化持续getopts为好。您可能应该在循环之前执行一次,然后将

set +f

之后。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章