bash函数不识别输入

时间:2018-04-06 06:15:39

标签: bash

我似乎在终端上执行这个bash函数时遇到了一些问题,

function sort () {

if [ "$#" -ne 1 ]; 
then
    word="$arg1"
    isolated="$arg2"
    file="output/$word _ $isolated_matches"
else
    word="$arg1"
    file="output/$word_matches"
fi
echo "$word"
echo "$file"
cat "$file" | while read line;
do
output=$(awk 'BEGIN{IGNORECASE=1} /"$word"/ {print NR, $0}' "$line");
if [ $[#output] -ne 0 ];
then
    echo "File: " "$line";
    echo "----------------------------------------------------";
    echo "$output";
fi
echo $'\n';

done

我在终端中输入脚本,当我执行

 sort a a 

我的输出变为:

output
cat: output/ Is a directory

为什么它不能识别我给出的输入?

1 个答案:

答案 0 :(得分:0)

请检查此更改。

#!/bin/bash

function sort () {

if [ "$#" -ne 1 ]; 
then
    word=$1
    isolated=$2
    file="output/${word}_${isolated}_matches"
else
    word="$1"
    file="output/${word}_matches"
fi

touch "$file"

echo "word : $word"
echo "file : $file"
cat "$file" | while read line;

do
    output=$(awk -v word="$word";  BEGIN{IGNORECASE=1} /"$word"/ {print NR, $0}' "$line");
    if [ -n "$output" ];
        then
            echo "File: " "$line";
            echo "----------------------------------------------------";
            echo "$output";
        fi
    echo $'\n';
done

}

<强>输出

smily@Machine MINGK64 /d/test
$ sh testbash.sh
word : a
file : output/a_a_matches