Skip to content

Commit

Permalink
feat: Enhance config file modification with special character escaping
Browse files Browse the repository at this point in the history
- Added robust character escaping for keys and values in JSON configuration
- Used sed to safely handle special characters during file modification
- Improved reliability of modify_or_add_config function
- Prevented potential sed parsing errors with advanced escaping techniques
  • Loading branch information
yuaotian committed Feb 18, 2025
1 parent 1789719 commit d83c95e
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions scripts/run/cursor_linux_id_modifier.sh
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,10 @@ modify_or_add_config() {
local value="$2"
local file="$3"

# 转义特殊字符
local key_escaped=$(sed 's/[\/&]/\\&/g' <<< "$key")
local value_escaped=$(sed 's/[\/&]/\\&/g' <<< "$value")

if [ ! -f "$file" ]; then
log_error "文件不存在: $file"
return 1
Expand All @@ -183,15 +187,15 @@ modify_or_add_config() {

# 检查key是否存在
if grep -q "\"$key\":" "$file"; then
# key存在,执行替换
sed "s|\"$key\":[[:space:]]*\"[^\"]*\"|\"$key\": \"$value\"|" "$file" > "$temp_file" || {
# 使用#作为分隔符避免冲突,并转义特殊字符
sed "s#\"${key_escaped}\":[[:space:]]*\"[^\"]*\"#\"${key_escaped}\": \"${value_escaped}\"#" "$file" > "$temp_file" || {
log_error "修改配置失败: $key"
rm -f "$temp_file"
return 1
}
else
# key不存在,添加新的key-value对
sed "s/}$/,\n \"$key\": \"$value\"\n}/" "$file" > "$temp_file" || {
# 添加新键值对时转义特殊字符
sed "s/}$/,\n \"${key_escaped}\": \"${value_escaped}\"\n}/" "$file" > "$temp_file" || {
log_error "添加配置失败: $key"
rm -f "$temp_file"
return 1
Expand Down

0 comments on commit d83c95e

Please sign in to comment.