gpt4 book ai didi

linux - 在 bash 脚本中连接 var 时出错

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:41:10 26 4
gpt4 key购买 nike

我有一个 bash 脚本,用于搜索 unrar 文件的密码。我想连接结果并在脚本结束时通知执行结果,但我不知道为什么 final_result var 输出“INIT-END”。

为什么不在 search_pass_and_unrar 函数中连接?

#!/bin/bash

# Url for finding rar files
url_hdd="/media/HDD"
final_result="INIT-"

unrar_files(){

filebase=`dirname "$1"`
url_rar="$1"
url_for_pass=""

# Search files for password
find "$filebase" -name '*CONTR*.txt' | while read LINE; do

# Convert Windows line ending
$(sed -i 's/^M//g' "$LINE")

# Get url where we can find file password
url_for_pass=$(cat "$LINE" | grep -Eo '(http|https)://[^?"]+')

search_pass_and_unrar "$url_for_pass" "$url_rar" "$filebase"

done

}

search_pass_and_unrar(){

final_url="$1"
pass=$(curl -s -S -L "$final_url" | grep 'name="txt_password"' | grep -oP 'value="\K[^"]+')

if [[ -z "$pass" ]]
then
final_result+="Error, password not found"
return
fi

result_unrar=$(unrar e "${2}" "${3}" -p"${pass}")
final_result+="Result: ${result_unrar}"


}

# Find rar files and call unrar_files function
find "$url_hdd" -type f -name "*.rar" | while read LINE; do
unrar_files "$LINE"
done

final_result+="END"
echo "$final_result" # "INIT-END"

非常感谢,最好的问候。

最佳答案

问题在这里:

# Find rar files and call unrar_files function
find "$url_hdd" -type f -name "*.rar" | while read LINE; do
unrar_files "$LINE"
done

由于此处使用的管道,您的脚本正在派生另一个子 shell 并在子 shell 中调用 unrar_files。由于此子 shell 创建,对 final_result 所做的所有更改在当前 shell 中都不可见。

您可以像这样使用进程替换来修复它:

# Find rar files and call unrar_files function
while IFS= read -d '' -r LINE; do
unrar_files "$LINE"
done < <(find "$url_hdd" -type f -name '*.rar' -print0)

注意使用 -print0 来确保我们也可以处理带有特殊字符的文件。

同样在 unrar_files 中,您需要这样做:

while IFS= read -d '' -r LINE; do

# Convert Windows line ending
$(sed -i 's/^M//g' "$LINE")

# Get url where we can find file password
url_for_pass=$(cat "$LINE" | grep -Eo '(http|https)://[^?"]+')

search_pass_and_unrar "$url_for_pass" "$url_rar" "$filebase"

done < <(find "$filebase" -name '*CONTR*.txt' -print0)

关于linux - 在 bash 脚本中连接 var 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42652107/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com