简体   繁体   中英

Bash-script File creation and fill

I am trying to write a bash-script which will create a certain number of files which are passed into an argument, and also fill that file with relevant information. However, for some reason I can't get it to work properly, and googling turned up nothing.

I want it to create files like the following: FileName:

Prob_3_ch_17.cpp

Filled as the following:

/*
User: Johnny Smith
Prob: 3
Output: 
*/

Where the first command line argument is the chapter number. The second is the starting number, and the third is the ending number. So if the following is ran

sh ../FileMaker.sh 17 1 10

It will make 10 files, each filled with the appropriate data and proper file names, for chapter 17. This is the script that I came up with.

#!/bin/bash

# Syntax:
# $1 = Chapter Number
# $2 = Starting Number
# $3 = Ending Number

CHAPTER=$1
FIRST=$2
LAST=$3
U_NAME="Johnny Smith"

# Name: Prob_$NUMBER_Ch_$1.cpp

for ((NUMBER=$FIRST; $NUMBER<=$LAST; $NUMBER++));
   do
      if [ -e "Prob_$NUMBER_Ch_$CHAPTER.cpp" ]; then
         echo "File Prob_$NUMBER_Ch_$CHAPTER.cpp already exists!"
      else
         echo "/* \n User: $U_NAME \n Problem: $NUMBER \n Output: \n */" >> "Prob_$NUMBER_Ch_$CHAPTER.cpp"
   done

However, it doesn't run. I get the following error:

../FileMaker.sh: line 21: syntax error near unexpected token `done'
../FileMaker.sh: line 21: `done'

I've googled and found other people have had the same problem, but I didn't fully understand what was meant in the solution. Can someone please help me? I'm not the best at shell scripting, and I'm trying to learn by making scripts like this.

Thanks in advanced.

Syntax for if block and for-loop is wrong. correct syntax would be -

    for ((NUMBER=FIRST; NUMBER<=LAST; NUMBER++));
   do
      if [ -e "Prob_$NUMBER_Ch_$CHAPTER.cpp" ]; then
         echo "File Prob_$NUMBER_Ch_$CHAPTER.cpp already exists!"
      else
         echo "/* \n User: $U_NAME \n Problem: $NUMBER \n Output: \n */" >> "Prob_$NUMBER_Ch_$CHAPTER.cpp"
      fi
   done

See example 11.12 for c style for loop.

To create files use "Prob_"$NUMBER" Ch "$CHAPTER".cpp" at all the places.

Most shells allow a set -x at the top. This show you tracing of the script as it executes.

  1. You need a trailing fi to close the if statement.
  2. Shell math need NUMBER=$(expr $NUMBER + 1) , it doesn't understand $NUMBER++ .
  3. You might find the printf command more handy than echo .

You will still have your variable use wrong in the loop and are only creating one file. I hope you can figure that out as this seems like homework.

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