我编写了以下shell脚本,以在每个软件包的目录中执行给定的命令集。如果任何命令失败,它应该停止。它还应该在控制台上显示命令输出。
它需要3个带有选项的参数
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"
)
这是一个棘手的问题。:)
您IFS
在getopts
循环中进行了更改,但从未将其更改回旧值。所以当你写:
$1
在中executeCommand
,它不会将空格视为cd
和参数之间的分隔符。
完成后,您需要将其设置回默认值getopts
:
IFS=$' \t\n'
在set -f
之后的变化持续getopts
为好。您可能应该在循环之前执行一次,然后将
set +f
之后。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句