简体   繁体   English

用于递减传递的参数的Shell脚本

[英]Shell Script for counting down passed argument

So I was working on a project tonight and assumed based on my poor understanding that the requirement was to create a script to take a number and count down to 1 with commas on the same line. 因此,我今晚在一个项目上工作,并基于对我的理解不足而假定,要求是创建一个脚本以接受数字并在同一行上用逗号将数字减至1。

A few people here introduced me to the seq command and I was on my way. 这里有几个人向我介绍了seq命令,而我正在路上。

Turns out it needs to take the variable integer from a command line argument. 事实证明,它需要从命令行参数中获取变量整数。

What I have now: 我现在所拥有的:

#!/bin/bash
#countdown

read -p "Enter a Number great than 1: " counter

seq -s, $counter -1 

Needs to work by taking an argument after the line, such as /assign1p1 5 and then outputting 5,4,3,2,1 需要通过在该行之后输入一个参数来工作,例如/ assign1p1 5然后输出5,4,3,2,1

I've seen the $1 used as an argument marker? 我看过$ 1用作参数标记吗? Is that how to work from it? 那是如何工作的?

Use Three Arguments 使用三个参数

The correct call to seq for your use case is: 针对您的用例,对seq的正确调用是:

seq [OPTION]... FIRST INCREMENT LAST seq [OPTION] ...第一次增加

To decrement your starting value down to 1 using the defined separator, try something similar to this example: 要使用定义的分隔符将起始值减小到1,请尝试类似于以下示例:

$ set -- 5
$ seq -s, $1 -1 1
5,4,3,2,1

Obviously, the call to set won't be needed inside the script, but is a great way to test at the command line. 显然,脚本内部不需要调用set ,但是这是在命令行中进行测试的好方法。

The command-line arguments passed to your script are $1 , $2 , etc. 传递给脚本的命令行参数为$1$2等。

#!/bin/bash

seq -s, $1 1
echo

If you want to make this more robust you might want to verify that the user passed in the correct number of arguments, which is the variable $# . 如果要使其更健壮,则可能需要验证用户是否传入了正确数量的参数,即变量$#

#!/bin/bash

if (( $# != 1 )); then
    echo "Usage: $0 num" >&2
    exit 1
fi

seq -s, $1 1
echo

Arguments passed to the script from the command line include : $0, $1, $2, $3 . 从命令行传递到脚本的参数包括:$ 0,$ 1,$ 2,$ 3。 . .

$0 is the name of the script itself, $1 is the first argument, $2 the second, $3 the third, and so forth. $ 0是脚本本身的名称,$ 1是第一个参数,$ 2是第二个参数,$ 3是第三个参数,依此类推。 [2] After $9, the arguments must be enclosed in brackets, for example, ${10}, ${11}, ${12}. [2]在$ 9之后,参数必须放在方括号中,例如$ {10},$ {11},$ {12}。

If for whatever reason you do not want to use seq 如果出于某种原因您不想使用seq

a=$1
for (( b = a; b > 0; b-- ))
do
  (( b == a )) || printf ,
  printf $b
done

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

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