我正在尝试编写一个bash脚本,在该脚本中,用户输入一个类名,它会生成正确的.h
和.cpp
文件。
我已经大部分工作了,但是当我运行它时,出现了错误:
./makeClass.sh
:第20行:#include ${className.h}
:错误替换
生成的.h
文件具有所有预期的内容,而.cpp
文件的生成在该行中止。
我尝试将${className.h}
替换为$(className.h)
,但这没用。
我也尝试连接字符串,但是我没有运气。
感谢您的所有帮助!
#!/bin/bash
echo "Please enter the name of the class to be created"
read className
touch $className.h
echo "#include <iostream>" >> $className.h
echo "#ifndef SICT_${className^^}_H" >> $className.h
echo "#define SICT_${className^^}_H" >> $className.h
echo "namespace sict {" >> $className.h
echo "class ${className^} {" >> $className.h
echo " " >> $className.h
echo "public: " >> $className.h
echo " };" >> $className.h
echo "}" >> $className.h
echo "#endif" >> $className.h
# Note: ${className^} converts the first letter to uppercase ${className^^}
# converts the whole string to upper case
touch $className.cpp
echo "#include ${className.h}" >> $className.cpp
echo "#include <iostream>" >> $className.cpp
echo "using namespace sict;" >> $className.cpp
echo "using namespace std;" >> $className.cpp
echo "namespace sict {" >> $className.cpp
echo "" >> $className.cpp
echo "}" >> $className.cpp
错误消息:./makeClass.sh:第20行:#include $ {className.h}:替代错误
答案 0 :(得分:2)
您的错误是:
echo "#include ${className.h}" >> $className.cpp`
^
它将威胁整个className.h
作为变量名,并且在变量名中不允许使用点字符.
。
除非您希望它解释转义,否则请始终将-r
标志添加到read
。
您可以使用此处文档扩展bash变量值来更清晰,更有效地创建模板:
尽管,如果您需要一个实际的美元符号$
文字,则需要将其转义为\$
,否则bash会尝试将变量名扩展为其值。
#!/usr/bin/env bash
echo "Please enter the name of the class to be created"
read -r className
cat <<EndOfClassHeader >"$className.h"
#include <iostream>
#ifndef SICT_${className^^}_H
#define SICT_${className^^}_H
namespace sict {
class ${className^} {
public:
};
}
#endif
EndOfClassHeader
cat <<ENdOfClassCPP >"$className.cpp"
#include ${className}.h
#include <iostream>
using namespace sict;
using namespace std;
namespace sict {
}
ENdOfClassCPP
答案 1 :(得分:0)
这将始终有效
echo "#include \"$className.h\"" >> $className.cpp
解释:由于
className.h
是一个变量,使用时请使用双引号,并且这里echo
已经有双引号, 对该变量使用双引号。
完整代码
#!/bin/bash
echo "Please enter the name of the class to be created"
read className
touch $className.h
echo "#include <iostream>" >> $className.h
echo "#ifndef SICT_${className^^}_H" >> $className.h
echo "#define SICT_${className^^}_H" >> $className.h
echo "namespace sict {" >> $className.h
echo "class ${className^} {" >> $className.h
echo " " >> $className.h
echo "public: " >> $className.h
echo " };" >> $className.h
echo "}" >> $className.h
echo "#endif" >> $className.h
# Note: ${className^} converts the first letter to uppercase ${className^^}
# converts the whole string to upper case
touch $className.cpp
echo "#include \"$className.h\"" >> $className.cpp
echo "#include <iostream>" >> $className.cpp
echo "using namespace sict;" >> $className.cpp
echo "using namespace std;" >> $className.cpp
echo "namespace sict {" >> $className.cpp
echo "" >> $className.cpp
echo "}" >> $className.cpp