RHEL 7 Bash скрипт не распознает $ args - PullRequest
0 голосов
/ 05 марта 2020

Ниже приведена моя простая функция для получения введенного пользователем имени файла, но по какой-то причине моя проверка ввода не работает.

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")

Why is ' Это работает?

Спасибо!

1 Ответ

0 голосов
/ 06 марта 2020

Есть много способов игнорировать детали после пробелов (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 guys ...):

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

БЗ

...