2016-05-07 2 views
1

Эй, я пытался смоделировать простую систему управления библиотекой, используя Shell Script, как часть моего назначения в UNIX в колледже, но у меня возникают странные ошибки в скрипте.Управление библиотекой с использованием Shell Script

Вот мой сценарий

menu_choice="" 
record_file="bookRecords.ldb" 
temp_file=/tmp/ldb.$$ 
trap 'rm -f $temp_file' EXIT 


get_return(){ 
printf '\tPress return\n' 
read x 
return 0 
} 
  
get_confirm(){ 
printf '\tAre you sure?\n' 
while true 
do 
  read x 
  case "$x" in 
      y|yes|Y|Yes|YES) 
     return 0;; 
      n|no|N|No|NO) 
          printf '\ncancelled\n' 
          return 1;; 
      *) printf 'Please enter yes or no';; 
  esac 
done 
} 

set_menu_choice(){ 
clear 
printf 'Options:-' 
printf '\n' 
printf '\ta) Add new Books records\n' 
printf '\tb) Find Books\n' 
printf '\tc) Edit Books\n' 
printf '\td) Remove Books\n' 
printf '\te) View Books\n' 
printf '\tf) Quit\n' 
printf 'Please enter the choice then press return\n' 
read menu_choice 
return 
} 

insert_record(){ 
echo $* >>$record_file 
return 
} 
  
  
#!!!!!!!!!...........................!!!!!!!!!!!!!!!! 
#This function ask user for details information about book for keeping records 
  
add_books(){ 
  
#prompt for information 
  
printf 'Enter Books category:-' 
read tmp 
liCatNum=${tmp%%,*} 
  
printf 'Enter Books title:-' 
read tmp 
liTitleNum=${tmp%%,*} 
  
printf 'Enter Auther Name:-' 
read tmp 
liAutherNum=${tmp%%,*} 
  
#Check that they want to enter the information 
printf 'About to add new entry\n' 
printf "$liCatNum\t$liTitleNum\t$liAutherNum\n" 
  
#If confirmed then append it to the record file 
if get_confirm; then 
   insert_record $liCatNum,$liTitleNum,$liAutherNum 
fi 
  
return 
} 

find_books(){ 
grep computer $record_file > $temp_file 
     
  set $(wc -l $temp_file) 
  linesfound=$1 
  
  case "$linesfound" in 
  0)    echo "Sorry, nothing found" 
        get_return 
        return 0 
        ;; 
  *)    echo "Found the following" 
        cat $temp_file 
        get_return 
        return 0 
  esac 
return 
} 


$temp_file 
  
 set $(wc -l $temp_file) 
   linesfound=$1 
  
   case "$linesfound" in 
   0)    echo "Sorry, nothing found\n" 
         get_return 
         return 0 
         ;; 
   *)    echo "Found the following\n" 
         cat $temp_file ;; 
        esac 
 printf "Type the books titel which you want to delete\n" 
 read searchstr 
  
  if [ "$searchstr" = "" ]; then 
      return 0 
   fi 
 grep -v "$searchstr" $record_file > $temp_file 
 mv $temp_file $record_file 
 printf "Book has been removed\n" 
 get_return 
return 
} 
  
view_books(){ 
printf "List of books are\n" 
  
cat $record_file 
get_return 
return 
} 



edit_books(){ 
  
printf "list of books are\n" 
cat $record_file 
printf "Type the tile of book you want to edit\n" 
read searchstr 
  if [ "$searchstr" = "" ]; then 
     return 0 
  fi 
  grep -v "$searchstr" $record_file > $temp_file 
  mv $temp_file $record_file 
printf "Enter the new record" 
add_books 
  
} 

rm -f $temp_file 
if [!-f $record_file];then 
touch $record_file 
fi 
  
clear 
printf '\n\n\n' 
printf 'Mini library Management' 
sleep 1 
  
quit="n" 
while [ "$quit" != "y" ]; 
do 
  
#funtion call for choice 
set_menu_choice 
case "$menu_choice" in 
a) add_books;; 
b) find_books;; 
c) edit_books;; 
d) remove_books;; 
e) view_books;; 
f) quit=y;; 
*) printf "Sorry, choice not recognized";; 
esac 
done 
# Tidy up and leave 
  
rm -f $temp_file 
echo "Finished" 
  
exit 0 

ошибка при выполнении:

manage.sh: line 12:  : command not found 
manage.sh: line 19: syntax error near unexpected token `)' 
manage.sh: line 19: `      y|yes|Y|Yes|YES) ' 

И любые дальнейшие предложения по улучшению скрипта будет хорошо оценены.

+3

Пожалуйста, обратите внимание: http://www.shellcheck.net/ – Cyrus

+0

У вас есть '$ temp_file', за которым следует' set $ (wc -l $ temp_file) '. Вам нужно создать файл, иначе 'wc' вернет ошибку. Вы имели в виду '> $ temp_file'? – cdarke

+0

престиж за то, что у вас большой патрон кода для вашего задания. Есть много вещей, чтобы прокомментировать, но я выберу только одну тему ('return'). A. Принципы Unix/Linux/std-coding-practices говорят «return 1» (или другое ненулевое), чтобы указать условие ошибки. Вы возвращаете '0' всюду. B. имея 'return' в качестве последней строки функции (без возврата значения переменной), всегда будет возвращать' 0' и является избыточным (unneeded), поскольку функция вернет '0' по умолчанию (без какого-либо кода). Меньше кода почти всегда лучше. Удачи! – shellter

ответ

0

звучит для меня, как будто вы используете какую-то другую оболочку, чем bash. строка 12 является окончанием определения функции до bash, но не к примеру. до csh, что дает }: Command not found. аналогичным образом, bashcase синтаксис bash -специфический и, например, csh ошибок в строке 19 с помощью: Too many)'s. Это не точные ошибки, которые вы получаете, поэтому вы не используете csh, но вы, вероятно, тоже не используете bash. попробуйте вызвать вашу программу:

bash manage.sh 

или, лучше, сделайте следующее:

`which bash` 

затем поместить результат того, что на первой строке сценария после #!, например,

#!/bin/bash 

или:

#!/usr/local/bin/bash 

в зависимости от того, где bash находится в вашей системе.

затем сделать это один раз:

chmod +x manage.sh 

и вызывать сценарий как этот Впредь:

./manage.sh 
0

Скрипт имеет некоторые явные проблемы,

  • добавьте следующие строки в следующем to temp_file =/tmp/ldb. $$, чтобы создать пустой файл и предоставить необходимое разрешение.

    touch $temp_file ; 
    chmod 644 $temp_file 
    
  • Просто рядом с определением функции из remove_books(), вы пытаетесь Выполнить $ temp_file, которые я думаю, вы не собираетесь делать. удалить строку '$ temp_file'
  • Кажется, вы пропустили начальный блок для функции find_books().
  • Вы пытаетесь найти количество строк в файле Ldb, выполнив следующие строки

    set $(wc -l $temp_file) 
    linesfound=$1 
    

    whcih не кажется правильным.Вместо того, чтобы вы могли достичь выполнения ниже линии,

    linesfound=`cat $temp_file|wc -l` 
    

Вот модифицированный скрипт с быстрым исправлением,

menu_choice="" 
record_file="bookRecords.ldb" 
temp_file=/tmp/ldb.$$ 
touch $temp_file; chmod 644 $temp_file 
trap 'rm -f $temp_file' EXIT 


get_return(){ 
printf '\tPress return\n' 
read x 
return 0 
} 

get_confirm(){ 
printf '\tAre you sure?\n' 
while true 
do 
    read x 
    case "$x" in 
     y|yes|Y|Yes|YES) 
     return 0;; 
     n|no|N|No|NO) 
      printf '\ncancelled\n' 
      return 1;; 
     *) printf 'Please enter yes or no';; 
    esac 
done 
} 

set_menu_choice(){ 
clear 
printf 'Options:-' 
printf '\n' 
printf '\ta) Add new Books records\n' 
printf '\tb) Find Books\n' 
printf '\tc) Edit Books\n' 
printf '\td) Remove Books\n' 
printf '\te) View Books\n' 
printf '\tf) Quit\n' 
printf 'Please enter the choice then press return\n' 
read menu_choice 
return 
} 

insert_record(){ 
echo $* >>$record_file 
return 
} 


#!!!!!!!!!...........................!!!!!!!!!!!!!!!! 
#This function ask user for details information about book for keeping records 

add_books(){ 

#prompt for information 

printf 'Enter Books category:-' 
read tmp 
liCatNum=${tmp%%,*} 

printf 'Enter Books title:-' 
read tmp 
liTitleNum=${tmp%%,*} 

printf 'Enter Auther Name:-' 
read tmp 
liAutherNum=${tmp%%,*} 

#Check that they want to enter the information 
printf 'About to add new entry\n' 
printf "$liCatNum\t$liTitleNum\t$liAutherNum\n" 

#If confirmed then append it to the record file 
if get_confirm; then 
    insert_record $liCatNum,$liTitleNum,$liAutherNum 
fi 

return 
} 

find_books(){ 
    echo "Enter book title to find:" 
    read book2find 
    grep $book2find $record_file > $temp_file 

    # set $(wc -l $temp_file) 
    # linesfound=$1 
    linesfound=`cat $temp_file|wc -l` 

    case `echo $linesfound` in 
    0) echo "Sorry, nothing found" 
     get_return 
     return 0 
     ;; 
    *) echo "Found the following" 
     cat $temp_file 
     get_return 
     return 0 
    esac 
return 
} 

remove_books() { 
# $temp_file 

    #set $(wc -l $temp_file) 
    #linesfound=$1 
    linesfound=`cat $record_file|wc -l` 

    case `echo $linesfound` in 
    0) echo "Sorry, nothing found\n" 
     get_return 
     return 0 
     ;; 
    *) echo "Found the following\n" 
     cat $record_file ;; 
     esac 
printf "Type the books titel which you want to delete\n" 
read searchstr 

    if [ "$searchstr" = "" ]; then 
     return 0 
    fi 
grep -v "$searchstr" $record_file > $temp_file 
mv $temp_file $record_file 
printf "Book has been removed\n" 
get_return 
return 
} 

view_books(){ 
printf "List of books are\n" 

cat $record_file 
get_return 
return 
} 



edit_books(){ 

printf "list of books are\n" 
cat $record_file 
printf "Type the tile of book you want to edit\n" 
read searchstr 
    if [ "$searchstr" = "" ]; then 
    return 0 
    fi 
    grep -v "$searchstr" $record_file > $temp_file 
    mv $temp_file $record_file 
printf "Enter the new record" 
add_books 

} 

rm -f $temp_file 
if [!-f $record_file];then 
touch $record_file 
fi 

clear 
printf '\n\n\n' 
printf 'Mini library Management' 
sleep 1 

quit="n" 
while [ "$quit" != "y" ]; 
do 

#funtion call for choice 
set_menu_choice 
case "$menu_choice" in 
a) add_books;; 
b) find_books;; 
c) edit_books;; 
d) remove_books;; 
e) view_books;; 
f) quit=y;; 
*) printf "Sorry, choice not recognized";; 
esac 
done 
# Tidy up and leave 

rm -f $temp_file 
echo "Finished" 

exit 0