簡體   English   中英

如何防止用戶在bash腳本中什么也不輸入

[英]How to prevent user to input nothing in bash script

我有一個程序,它將使用用戶輸入字符串並相應地創建輸出文件,例如“ ./bashexample2 J40087”,它將為文件夾中包含字符串J40087的所有文件創建輸出文件。 一個問題是,如果用戶未在輸入字符串中輸入任何內容,它將為包含文件夾中的每個文件生成輸出文件。 有沒有一種方法可以防止用戶在輸入字符串中什么也不輸入? 或者也許會發出一些警告,說“請輸入輸入字符串”。

#Please follow the following example as input: xl-irv-05{kmoslehp}312: ./bashexample2    J40087

#!/bin/bash

directory=$(cd `dirname .` && pwd) ##declaring current path
tag=$1 ##declaring argument which is the user input string

echo find: $tag on $directory ##output input string in current directory.

find $directory . -maxdepth 0 -type f -exec grep -sl "$tag"  {} \; ##this finds the string the user requested 
for files in "$directory"/*"$tag"* ##for all the files with input string name...
do
    if [[ $files == *.std ]]; then ##if files have .std extensions convert them to .sum files...
            /projects/OPSLIB/BCMTOOLS/sumfmt_linux < "$files" > "${files}.sum"
    fi

    if [[ $files == *.txt ]]; then  ## if files have .txt extensions grep all fails and convert them..
        egrep "device|Device|\(F\)" "$files" > "${files}.fail"
        fi
        echo $files ##print all files that we found
done

我會做這樣的事情:

tag=$1

if [ -z "$tag" ]; then
  echo "Please supply a string"
  exit 1
fi

您可以使用$#知道已將多少個參數作為參數傳遞,然后詢問是否至少有一個參數。

例如

if [ $# -gt 0 ]; then
    ... your logic here ...

另外,您可以使用$ 1讀取傳遞給腳本的第一個參數,第二個使用$ 2讀取,依此類推。

希望能有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM