【问题标题】:Bashing redirecting output to a program抨击将输出重定向到程序
【发布时间】:2014-04-24 21:46:05
【问题描述】:

为什么不读取文本文件。这里更好的方法是我的代码。 我正在尝试使用 for 读取一行,但它似乎不起作用

if [[ "$#" -ne 1 ]]
then
    writeusage
    exit
fi
your_path=../file/test1
test_path=../../public/test1
file_input="$1"
while read -r line
do
   args+="$line"
done < "$file_input"
# Redirect the output to a file named text
$test_path > correctanswer 2>&1
# Redirect your output to a file named text2
$your_path > youranswer 2>&1
# diff the solutions
diff correctanswer youranswer

【问题讨论】:

  • 仅供参考,全大写的变量名仅适用于环境变量和内置函数;对于进程局部变量,请考虑使用全小写名称以避免潜在的命名空间冲突。
  • 另外,请参阅mywiki.wooledge.org/BashFAQ/050 -- $YOUR_PATH$args 几乎是不符合定义的。
  • 嗯,我明白了,谢谢你的提示你知道我为什么遇到新问题吗?
  • 如果你想要每个参数一行,用args=()初始化,用args+=( "$line" )追加,用"$your_path" "${args[@]}"调用。请注意,这不允许您使用包含文字换行符的参数——如果您想要一种允许表示任何和所有可能参数的文件格式,您需要使用 NUL 分隔符来分隔您的参数,而不是换行符分隔符。
  • 这个问题是一系列密切相关但不重复的问题之一:SO 23282867SO 23281913SO 23280857SO 23280484

标签: bash scripting


【解决方案1】:
(( $# == 1 )) || { writeusage; exit 1; }

your_path=../file/test1
test_path=../../public/test1
file_input="$1"

# for bash older than 4.x
while read -r line; do
   args+=( "$line" )
done < "$file_input"

## ...for newer bash, you could do this instead:
# readarray -t args <"$file_input"

# Redirect the output to a file named text
"$test_path" "${args[@]}" > correctanswer 2>&1
# Redirect your output to a file named text2
"$your_path" "${args[@]}" > youranswer 2>&1
# diff the solutions
diff correctanswer youranswer

【讨论】:

    【解决方案2】:

    您需要将 for 循环更改为:

    while read -r line
    do
       args+="$line"
    done < "$FILE_INPUT"
    

    【讨论】:

    • 你能解释一下我在做什么吗?
    • @user3281743,不,这不容易解释,因为你所做的在很大程度上取决于文件的内容,也取决于你的文件系统(例如,如果文件中的任何内容都可以被解释作为适用于本地文件系统的全局,这会改变事情)。
    • 嗯,现在我在 $TEST_PATH$args >>correctanswer 2>&1 # 将您的输出重定向到名为 text2 $YOUR_PATH$args >> youranswer 2>&1 的文件中的错误文件或目录我的 $TEST_PATH=../../test 但它说找不到 ../../test9 为什么它在末尾添加 9?
    • 您的脚本有很多问题。你能告诉我$TEST_PATH$args 在做什么吗?
    • 其实我也不知道,我只是看到了一个例子,稍微复制了一下,但我想实现的是在那个路径中将另一个输出直接输出到那个程序中
    猜你喜欢
    • 2020-10-24
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多