我正在编写一个 bash 脚本来使用 puppet 客户端引导云服务器,以便我可以创建一个引导映像,但是我从一个简单的“cp -r”中得到了奇怪的行为,其中我的源目录的内容是已复制,但未复制父目录。例如,如果我有 /root/puppet/file1,并且我cp -r /root/puppet /opt
在 bash 脚本中发出了一个命令,而不是得到 /opt/puppet/file1,我得到的是 /opt/file1。但是,如果我在脚本执行之前在脚本中回显该命令,然后复制该回显的输出并在命令行上运行它,那么我将按预期获得 /opt/puppet/file1。
这是我的目录结构。
mydirectory
- script.sh
- assets
- puppet
- file1
- file2
- file3
这是我脚本中的片段
#!/bin/bash
### VARIABLE INITIALIZATION
BOOTSTRAP_DIR="/opt/bootstrapping"
# Die with an error message
die()
{
echo "**** BOOTSTRAPPING FAILED ****"
echo -e "ERROR: ${2}"
exit ${1}
}
# check the return code of the previous command and die if != 0
check_errs()
{
if [ "${1}" -ne "0" ]; then
die ${1} "${2}"
fi
}
# Get the path of the directory from which this script is being executed
SCRIPT_PATH="`dirname \"$0\"`" # relative
check_errs $? "Could not get the relative path of the executing script"
SCRIPT_PATH="`( cd \"$SCRIPT_PATH\" && pwd )`" # absolutized and normalized
check_errs $? "Could not get the absolute path of the executing script"
### DEPLOY THE BOOTSTRAPPING FILES
if [ -d "${BOOTSTRAP_DIR}" ]; then
echo "Removing ${BOOTSTRAP_DIR}"
rm -rf ${BOOTSTRAP_DIR}
check_errs $? "Could not remove ${BOOTSTRAP_DIR}"
fi
if [ ! -d "${SCRIPT_PATH}/assets/puppet" ]; then
die 1 "Can not find ${SCRIPT_PATH}/assets/puppet"
fi
if [ ! -f "${SCRIPT_PATH}/assets/rc.local" ]; then
die 1 "Can not find ${SCRIPT_PATH}/assets/rc.local"
fi
# This command succeeds, but /opt/bootstrapping/puppet does not exist afterwards.
# Instead I get /opt/bootstrapping/files...
echo "Copying ${SCRIPT_PATH}/assets/puppet to ${BOOTSTRAP_DIR}"
cp -r ${SCRIPT_PATH}/assets/puppet ${BOOTSTRAP_DIR}
check_errs $? "Could not copy ${SCRIPT_PATH}/assets/puppet to ${BOOTSTRAP_DIR}"
echo "Copying ${SCRIPT_PATH}/assets/rc.local to /etc/rc.local"
cp ${SCRIPT_PATH}/assets/rc.local /etc/rc.local
check_errs $? "Could not copy ${SCRIPT_PATH}/assets/rc.local to /etc/rc.local"
谁能解释为什么只复制我的源目录的内容?我觉得这是一件愚蠢的事情,因为我累了所以我没有看到。
编辑
这绝对是我愚蠢的一个例子。当脚本调用cp -r /root/assets/puppet /opt/bootstrapping
时,/opt/bootstrapping 不存在,因此 cp 创建 /opt/bootstrapping,并将源文件放入该新目录。我认为这个问题在未来对任何人都没有多大价值。除非有人反对,否则我希望将其删除。