Bash、无参数警告和案例决定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2427995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:01:56  来源:igfitidea点击:

Bash, no-arguments warning, and case decisions

bash

提问by Open the way

I am learning bash.

我正在学习 bash。

I would like to do a simple script that, when not arguments given, shows some message. And when I give numers as argument,s depending on the value, it does one thing or another.

我想做一个简单的脚本,当没有给出参数时,会显示一些消息。当我根据值给出数字作为参数时,它会做一件事或另一件事。

I would also like to know suggestions for the best online manuals for beginners in bash

我还想知道有关 bash 初学者的最佳在线手册的建议

Thanks

谢谢

回答by Thomas

if [[ $# -eq 0 ]] ; then
    echo 'some message'
    exit 0
fi

case "" in
    1) echo 'you gave 1' ;;
    *) echo 'you gave something else' ;;
esac

The Advanced Bash-Scripting Guideis pretty good. In spite of its name, it does treat the basics.

高级Bash脚本编程指南是相当不错的。尽管它的名字,它确实处理基础知识。

回答by Pat

If only interested in bailing if a particular argument is missing, Parameter Substitutionis great:

如果只对缺少特定参数的情况感兴趣,则参数替换很棒:

#!/bin/bash
# usage-message.sh

: ${1?"Usage: 
 if [ -z "$*" ]; then echo "No args"; fi
ARGUMENT"} # Script exits here if command-line parameter absent, #+ with following error message. # usage-message.sh: 1: Usage: usage-message.sh ARGUMENT

回答by Trampas Kirk

Example

例子

No args

Result

结果

if [[  == "" ]] #Where "" is the positional argument you want to validate 

 then
 echo "something"
 exit 0

fi

Details

细节

-zis the unary operator for length of string is zero. $*is all arguments. The quotes are for safety and encapsulating multiple arguments if present.

-z是字符串长度为零的一元运算符。 $*都是论据。引号是为了安全和封装多个参数(如果存在)。

Use man bashand search (/key) for "unary" for more operators like this.

使用man bash和搜索(/键)“一元”以获得更多这样的运算符。

回答by Ryan Smith

Old but I have reason to rework the answer now thanks to some previous confusion:

旧的,但由于之前的一些混淆,我现在有理由重新编写答案:

##代码##

This will echo "Something" if there is no positional argument $1. It does not validate that $1 contains specific information however.

如果没有位置参数 $1,这将回显“Something”。但是,它不会验证 $1 是否包含特定信息。