【问题标题】:Bash - sometimes creates only empty outputBash - 有时只创建空输出
【发布时间】:2014-11-10 12:12:44
【问题描述】:

我正在尝试创建一个接受第一个参数并创建以该参数命名的文件的 bash 字典脚本,然后脚本接受下一个参数(它们是同一文件夹内的文件)并将它们的内容输出到文件中(第一个参数)。它还排序、删除符号等,但主要问题是,有时输出文件是空的(我传递一个非空文件和一个不存在的文件),在删除和运行脚本几次后,有时它有时是空的,有时不是。

#!/bin/bash

numberoffileargs=$(( $# - 1 ))
exitstat=0
counterexit=0
acceptingstdin=0;
> "$1";
#check if we have given input files given
if [ "$#" -gt 1 ]; then
    #for cycle going through input files
    for i in "${@:2}"
        do
    #check whether input file is readable
            if [ -r "${i}" ]; then
                cat "${i}" >> "$1"      
    #else redirect to standard output
            else
            exitstat=2
            counterexit=$((counterexit + 1))
            echo "file does not exist" 1>&2
            fi
       done 
else
    echo "stdin code to be done"
    acceptingstdin=1
        #stdin input to output file
#stdin=$(cat)
fi
    #one word for each line, alphabetical sort, alphabet only, remove duplicates
#all lowercase
#sort -u >> "$1"



if [ "$counterexit" -eq "$numberoffileargs" ] && [ "$acceptingstdin" -eq 0 ]; then 
    exitstat=3
fi
cat "$1" | sed -r 's/[^a-zA-Z\-]+/ /g' | tr A-Z a-z | tr ' ' '\n' | sort -u | sed '/^$/d'     > "$1"
echo "$numberoffileargs"
echo "$counterexit"
echo "$exitstat"
exit  $exitstat

【问题讨论】:

    标签: bash output


    【解决方案1】:

    这是您的脚本,其中有一些语法改进。你的麻烦来自字典在你的管道上的输入和输出。我添加了一个临时文件来修复它。

    #!/bin/bash
    
    (($# >= 1)) || { echo "Usage: $0 dictionary file ..." >&2 ; exit 1;}
    dict="$1"
    shift
    
    echo "Creating $dict ..."
    >| "$dict" || { echo "Failed." >&2 ; exit 1;}
    
    numberoffileargs=$#
    exitstat=0
    counterexit=0
    acceptingstdin=0
    
    if (($# > 0)); then
        for i ; do
            #check whether input file is readable
            if [ -r "${i}" ]; then
                cat "${i}" >> "$dict"
            else
                exitstat=2
                let counterexit++
                echo "file does not exist" >&2
            fi
        done 
    else
        echo "stdin code to be done"
        acceptingstdin=1
    fi
    
    if ((counterexit == numberoffileargs && acceptingstdin == 0)); then 
        exitstat=3
    fi
    
    sed -r 's/[^a-zA-Z\-]+/ /g' < "$dict" | tr '[:upper:]' '[:lower:]' | tr ' ' '\n' | 
    sort -u | sed '/^$/d' >| tmp$$
    
    mv -f tmp$$ "$dict"
    
    echo "$numberoffileargs"
    echo "$counterexit"
    echo "$exitstat"
    exit  $exitstat
    

    管道可能会得到改进。

    【讨论】:

    • 不知道为什么,但终端显示“第 19 行 - 目录或文件不存在”,重定向应该创建它,对吗?
    • 是的,这是我的猜测。
    猜你喜欢
    • 2013-01-08
    • 2016-11-22
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多