为什么$#总是返回0?

时间:2020-10-09 02:29:34

标签: bash arguments

我正在尝试编写仅接受一个参数的脚本。我还在学习,所以我不明白我的代码有什么问题。我不明白为什么,即使我更改了输入数量,代码也刚刚退出。 (注意:稍后,如果if语句,我将使用$ dir,但我没有将其包括在内。)

#!/bin/bash

echo -n "Specify the name of the directory"
read dir
if [ $# -ne 1 ]; then
        echo "Script requires one and only one argument"
        exit
fi

1 个答案:

答案 0 :(得分:0)

您可以使用https://www.shellcheck.net/仔细检查语法。

$#告诉您调用该脚本有多少个参数。 在这里,您有两个选择。


选项1 :使用参数

#!/bin/bash

if [[ $# -ne 1 ]]
then
    echo "Script requires one and only one argument"
    exit 1
else
    echo "ok, arg1 is $1"
fi
  • 要调用脚本,请执行以下操作:./script.bash argument
  • [[ ]]用于测试条件(http://mywiki.wooledge.org/BashFAQ/031
  • exit 1:默认情况下,当脚本存在状态码为0时,表示脚本可以正常工作。由于这是错误,因此请指定非零值。

选项2 :请勿使用参数,请向用户询问值。
注意:此版本完全不使用参数。

#!/bin/bash

read -r -p "Specify the name of the directory: " dir
if [[ ! -d "$dir" ]]
then
    echo "Error, directory $dir does not exist."
    exit 1
else
    echo "ok, directory $dir exists."
fi
  • 要调用脚本,请执行:./script.bash,不带任何参数。

您应该研究bash教程以学习如何使用参数。