1.背景:
Qt Creator ROS2 没有提供官方集成(2024-10-12),用 Github 开源插件 ros_qtc_plugin(参见我的另一篇博客 Ubuntu22 Qt6.6 ROS 插件, 使 Qt Creator 可编译ROS工程)。由于Qt 版本变化,插件突然失效,Qt 无法打开我的 ROS2 工程。没时间调研,暂时采取注释掉 CMakeLists 文件中ROS2 相关内容,Qt Creator 仅用来编辑 Qt UI 页面,命令行编译方式workaround。
Shell 脚本功能:修改CMakelists.txt,注释/取消注释 #ros2 start
和 #ros2 end
之间的内容(不包括这两行,以及其他注释)
2. sed 命令解释
# 使用sed取消注释ROS相关内容
sed -i '/#ros2 start/,/#ros2 end/{/^#ros2 start/!{/^#ros2 end/!s/^/#/}}' "$file" && \
echo "ROS content uncommented in $file"
这里的sed
命令使用了以下参数:
-i
:直接对文件进行编辑(in-place),不输出到标准输出。/#ros2 start/,/#ros2 end/
:指定了一个范围,从包含#ros2 start
的行开始,到包含#ros2 end
的行结束。{...}
:对范围内的行执行多个命令。/#ros2 start/d
:删除包含#ros2 start
的行。/#ros2 end/d
:删除包含#ros2 end
的行。s/^#//
:替换(substitute)操作,^#
表示每行开始的#
,空字符串表示要替换成的内容,即删除每行开始的#
来取消注释该行。
如果sed
命令执行成功,它将执行echo
命令,输出“ROS content uncommented in $file”。
3. 完整脚本
#!/bin/bash
comment_ros() {
local file="$1"
if [ -f "$file" ]; then
# 使用sed注释掉#ros2 start和#ros2 end之间的内容
sed -i '/#ros2 start/,/#ros2 end/{/^#ros2 start/!{/^#ros2 end/!s/^/#/}}' "$file" && \
echo "ROS content commented in $file"
else
echo "File not found: $file"
fi
}
uncomment_ros() {
local file="$1"
if [ -f "$file" ]; then
# 使用sed取消注释#ros2 start和#ros2 end之间的内容
sed -i '/#ros2 start/,/#ros2 end/{/^#ros2 start/!{/^#ros2 end/!s/^#//}}' "$file" && \
echo "ROS content uncommented in $file"
else
echo "File not found: $file"
fi
}
main() {
local action="$1"
local file_path="$2"
if [ -z "$file_path" ]; then
file_path="$(pwd)/CMakeLists.txt"
fi
if [ ! -f "$file_path" ]; then
file_path="/home/coco/myProjects/btl_ros_project/src/pkg_simulator_main_ui/CMakeLists.txt"
fi
if [ ! -f "$file_path" ]; then
echo "Default CMakeLists.txt not found. Please check the path."
return 1
fi
if [ "$action" == "-c" ]; then
echo "Commenting ROS content in $file_path"
comment_ros "$file_path"
elif [ "$action" == "-u" ]; then
echo "Uncommenting ROS content in $file_path"
uncomment_ros "$file_path"
else
echo "Usage: $0 <-c|-u> [<CMakeLists.txt path>]"
return 1
fi
}
if [ $# -lt 1 ]; then
echo "Usage: $0 <-c|-u> [<CMakeLists.txt path>]"
exit 1
fi
main "$@"
4.脚本使用 & 说明
1. 保存脚本
保存这个脚本为 toggle_ros_comments.sh
,并赋予执行权限:
chmod +x toggle_ros_comments.sh
2. 脚本输入参数说明
$1
是操作参数(-c
或 -u
),$2
是 CMakeLists.txt
文件的路径。如果没有提供路径,脚本将尝试在当前目录下查找 CMakeLists.txt
文件,如果找不到,则使用默认路径。
3. 使用示例
-
注释ROS相关内容:
./toggle_ros_comments.sh -c /path/to/your/CMakeLists.txt
或者,如果不提供路径:
./toggle_ros_comments.sh -c
-
取消注释ROS相关内容:
./toggle_ros_comments.sh -u /path/to/your/CMakeLists.txt
或者,如果不提供路径:
./toggle_ros_comments.sh -u