我编写了以下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"
)
答案 0 :(得分:1)
这是一个棘手的问题。 :)
您在IFS
循环期间更改了getopts
,并且从未将其更改回旧值。所以当你写:
$1
在executeCommand
中,它不会将空格视为cd
与其参数之间的分隔符。
完成getopts
后,您需要将其设置回默认值:
IFS=$' \t\n'
在set -f
之后,getopts
更改仍然存在。你应该在循环之前做一次,然后放
set +f
之后。