简体   繁体   中英

Writing a bash script

I need to write a simple bash script called finduser, where classlist is the name of the classlist file, and username is a particular student's username, either first name or last time. ./finduser classlist username

The script should

  • check that the correct number of arguments was received and print an error message if not,
  • check whether the classlist file exists and print an error message if not,
  • print the line of the given username in the classlist file

This is what I have so far but I am stuck!

#!/bin/bash
# check the correct number of arguments was received an print an error message if not
read classlist
echo "There are $# arguments"

# Check if the classlist file exusts and print error message if not
echo "checking if file exists"
        classlist=./classlist.txt
        if [ -f $classlist ]
        then
                 echo "$classlist exists."
        else echo "$classlist does not exist
        fi

# print the line of the given username

grep $2 $1

This is the text file

Alexander, Amy Elizabeth          BS      BADM          ACCT
Ayers, Brittany Nicole            BS      BADM          ACCT
Brown, Lyeshea Semondre Shayron   BS      BADM          ACCT
Calloway, Logan Mackenzie         BS      BADM          ACCT
Childers, Jamie Leigh             BS      BADM          ACCT

I'd do something like this

if [ "$#" -ne 2 ]; then
    echo "Usage:"
    echo "    $0 {filename} {username}"
    exit 1
fi

filename="$1"
username="$2"

if [ ! -f "${filename}" ]; then
    echo "Error: file ${filename} not found"
    exit 1
fi

grep "$username" "$filename"

Output for error handling:

$ ./stackoverflow.sh  in.cvs Leigh
Usage:
    ./stackoverflow.sh {filename} {username}

$ ./stackoverflow.sh  in2.cvs Le
Error: file in2.cvs not found

Output for success:

$ ./stackoverflow.sh  in.cvs Leigh
Childers, Jamie Leigh             BS      BADM          ACCT

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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