简体   繁体   English

bash/ksh 如果没有给定 echo 添加值的参数请添加

[英]bash/ksh add if no argument given echo add value please

I have this code for executing a single command using a number of different arguments:我有使用多个不同的 arguments 执行单个命令的代码:

for ((i = $#; i > 0 ; i--)) ; do
    grep -w -- "$1" codelist.lst || echo "'$1' not found"
    shift
done

This script gives me, for each argument, the correct output of either the lines containing the argument, or an indication that no lines were found.对于每个参数,此脚本为我提供包含该参数的行的正确 output,或者指示未找到任何行。

What I wish to add is a message if the user provided no arguments, such as "Please insert a value".如果用户没有提供 arguments,我想添加一条消息,例如“请插入一个值”。 How do I do that?我怎么做?

You can simply check $# before attempting to run the loop:您可以在尝试运行循环之前简单地检查$#

if [[ $# -eq 0 ]] ; then
    echo "Please insert a value."
else
    for ((i = $#; i > 0 ; i--)) ; do
        grep -w -- "$1" codelist.lst || echo "'$1' not found"
        shift
    done
fi

A zero value means that no arguments were provided.零值意味着没有提供 arguments。


An alternative form if you value simplicity of code is to realise that zero will also cause the loop body not to run even if the loop itself is executed, so you could do something like:如果您看重代码的简单性,另一种形式是意识到即使循环本身已执行,零也会导致循环体不运行,因此您可以执行以下操作:

[[ $# -eq 0 ]] && echo "Please insert a value."
for ((i = $#; i > 0 ; i--)) ; do
    grep -w -- "$1" codelist.lst || echo "'$1' not found"
    shift
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM