Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Shell 从文件或用户输入调用的脚本_Shell_Unix_Input - Fatal编程技术网

Shell 从文件或用户输入调用的脚本

Shell 从文件或用户输入调用的脚本,shell,unix,input,Shell,Unix,Input,我正在尝试编写一个小脚本,它要么从文件中获取输入,要么从用户处获取输入,然后从中删除任何空行 我正在尝试这样做,如果没有指定文件名,它将提示用户输入。另外,将手动输入输出到文件,然后运行代码或将其存储在变量中的最佳方式是什么 到目前为止,我有这个,但当我用一个文件运行它时,它会在返回我想要的输出之前给出一行错误。错误显示为/deblank:line 1:[blank_lines.txt:未找到命令 if [$@ -eq "$NO_ARGS"]; then cat > temporary

我正在尝试编写一个小脚本,它要么从文件中获取输入,要么从用户处获取输入,然后从中删除任何空行

我正在尝试这样做,如果没有指定文件名,它将提示用户输入。另外,将手动输入输出到文件,然后运行代码或将其存储在变量中的最佳方式是什么

到目前为止,我有这个,但当我用一个文件运行它时,它会在返回我想要的输出之前给出一行错误。错误显示为
/deblank:line 1:[blank_lines.txt:未找到命令

if [$@ -eq "$NO_ARGS"]; then  
cat > temporary.txt; sed '/^$/d' <temporary.txt  
else  
sed '/^$/d' <$@  
fi
如果[$@-eq“$NO_ARGS”];则
cat>temporary.txt;sed'/^$/d'尝试使用此

if [ $# -eq 0 ]; then  
  cat > temporary.txt; sed '/^$/d' <temporary.txt  
else  
  cat $@ | sed '/^$/d'  
fi
如果[$#-eq 0];那么

cat>temporary.txt;sed'/^$/d'您需要在
[
]
周围使用空格。在bash中,
[
是一个命令,您需要在其周围使用空格,以便bash对其进行解释

您还可以使用
(…)
检查是否存在参数。因此,您的脚本可以重写为:

if ((!$#)); then
  cat > temporary.txt; sed '/^$/d' <temporary.txt
else
  sed '/^$/d' "$@"
fi
如果((!$);那么

cat>temporary.txt;sed'/^$/d'此处存在多个问题:

  • 您需要在方括号[]和变量之间留一个空格

  • 使用字符串类型时,不能使用-eq,而是使用==

  • 使用字符串比较时,需要使用双方括号

  • 因此,代码应该如下所示:

    if [[ "$@" == "$NO_ARGS" ]]; then
    cat > temporary.txt; sed '/^$/d' <temporary.txt
    else
    sed '/^$/d' <$@
    fi
    
    如果[[“$@”==“$NO_ARGS”];则
    
    cat>temporary.txt;sed'/^$/d'不是强制用户输入文件,而是强制给定文件为stdin:

    #!/bin/bash
    
    if [[ $1  &&  -r $1 ]]; then
        # it's a file
        exec 0<"$1"
    elif ! tty -s; then
        : # input is piped from stdin
    else
        # get input from user
        echo "No file specified, please enter your input, ctrl-D to end"   
    fi
    
    # now, let sed read from stdin
    sed '/^$/d'
    
    !/bin/bash
    如果[[$1&&r$1]];则
    #这是一个文件
    
    exec 0LOL我用'if[$#-lt 1]'来处理它,但是你的代码更有意义,谢谢