【问题标题】:RHEL 7 Bash script not recognizing $argsRHEL 7 Bash 脚本无法识别 $args
【发布时间】:2020-03-05 17:20:46
【问题描述】:

以下是获取用户输入文件名的简单函数,但由于某种原因,我的输入验证不起作用。

function getname
{
        echo "Please enter the name of the file to install: "
        read filename
        if (($args > 1))
        then
                echo "You entered to many arguments."
                echo $USAGE
        exit
        fi
}

getname

Bash -x test1 产生这些结果,就好像它没有看到 $args 的任何值:

bash -x test1
+ getname
+ echo 'Please enter the name of the file to install: '
Please enter the name of the file to install:
+ read filename
testfile
+ ((  > 1 ))
test1: line 9: ((: > 1: syntax error: operand expected (error token is "> 1")

为什么这不起作用?

谢谢!

【问题讨论】:

  • 你在哪里将内容分配给变量 $args?
  • 在函数定义之前我有一个 args=$#.. 也许我做错了,$# 会返回命令行参数,但我没有传递任何参数。
  • 您的脚本有效。这意味着问题出在您未在此处显示的部分。
  • $# 返回 number 个命令行参数,而不是命令行参数。但根据跟踪,args 变量未设置为任何值。所以不,您没有args=$#(这会将args 设置为一个数字:0、1 等)。绝对不清楚您要实现什么 - 如果用户输入了多个单词,它们将全部存储在 filename 变量中。例如,尝试read f; echo "{$f}" 并输入foo bar

标签: linux bash shell scripting redhat


【解决方案1】:

有很多方法可以忽略空格后的部分(awk、cut、sed 可以完成工作),甚至警告这样的事情:

#!/bin/bash
echo "Input filename:"
read input
filename=$(echo $input | awk '{ print $1 }')
echo "Filename entered is: $filename"
[ "${filename}" != "${input}" ] && echo "(warning: parts after spaces were ignored)"

另外,使用read方便,你可以直接阅读你想要的:

read filename garbage

您可以考虑将空格转换为下划线(或将空格作为文件名的一部分,如 windows 家伙...):

read input
filename=$(echo $input | tr ' ' '_')

BR

【讨论】:

    猜你喜欢
    • 2022-11-22
    • 2023-03-13
    • 2015-09-10
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    相关资源
    最近更新 更多