Bash script: what's wrong with if condition?


Recommended Posts

Hii all. ..

I am learning shell programming. . .newbie though. ..

This is what I need to do. . .

I need to get "n" number of lines from the specified file and store the output to the new file in some other specified directory.. .and if the file with the same name exists. .the script should create a new file following with today's date. If the later file too exists,the new file should be created with incremental count to the end of the file.

Below is the script I came up with. But the problem is, all the files are created at once. i.e

abc

abc.20120729

abc.20120729.1

abc.20120729.2

Something is wrong with the if condition. . .can anyone let me know what ?

Thanks in advance. ..


#!/bin/bash

#USE : ./script_name path_to_file no_of_lines

export SAVEPATH="/home/zshaikh/"
export FILENAME=$(basename $1)
COUNT=1
if [ -r $FILE ]; then
tail -n $2 $1 >> ${SAVEPATH}${FILENAME}

elif [ -r ${SAVEPATH}${FILENAME} ]; then
tail -n $2 $1 > ${PATH}${FILENAME}.$(date +%Y%m%d)

elif [ -r ${SAVEPATH}${FILENAME}.$(date +%Y%m%d) ]; then
tail -n $2 $1 > ${PATH}${FILENAME}.$(date +%Y%m%d).$COUNT

elif [ -r ${SAVEPATH}${FILENAME}.$(date +%Y%m%d).$COUNT ]; then
COUNT=`expr $COUNT + 1`
tail -n $2 $1 > ${PATH}${FILENAME}.$(date +%Y%m%d).$COUNT

fi
[/CODE]

I don't have access to a bash interpreter at the minute, but I suspect it's breaking because you don't have a variable called "$FILE". This is causing the 'if' statement to break and just run all your tail commands. To fix this you'd normally put double-quotes round your if conditions (e.g. 'if [ -r "$FILE" ]; then ...')

I think the logic in your code is wrong though. It should be this:

#!/bin/bash

#USE : ./script_name path_to_file no_of_lines

export SAVEPATH="/home/zshaikh/"
export FILENAME=$(basename $1)
COUNT=1

# Check the file exists, and exit if it doesn't.
if ! [ -r "$1" ]; then
	echo "ERROR: File '${1}' does not exist!"
	exit 1
fi

# Check a second parameter is specified
if ! [ "$2" ]; then
	echo "ERROR: Number of lines not specified!"
fi

if  ! [ -e "${SAVEPATH}${FILENAME}" ]; then
	tail -n $2 $1 >> ${SAVEPATH}${FILENAME}
	echo "Written to ${SAVEPATH}${FILENAME}"

elif ! [ -e "${SAVEPATH}${FILENAME}.$(date +%Y%m%d)" ]; then
	tail -n $2 $1 > ${PATH}${FILENAME}.$(date +%Y%m%d)
	echo "Written to ${SAVEPATH}${FILENAME}.$(date +%Y%m%d)"

else
	while [ -e "${PATH}${FILENAME}.$(date +%Y%m%d).${COUNT}" ]; do
		COUNT=`expr $COUNT + 1`
	done
	tail -n $2 $1 > ${PATH}${FILENAME}.$(date +%Y%m%d).$COUNT
	echo "Written to ${SAVEPATH}${FILENAME}.$(date +%Y%m%d).$COUNT"
fi
[/CODE]

The code is untested, but should hopefully work.
Since you're a newbie, I hope you don't mind some constructive criticism. A few style points:Upper case variable names are a bad (even if common) practice. lower case variable names should be used, words separated with underscores. e.g. [code]
# This...
some_variable=1

# ... is better than ...
SOMEVARIABLE=1

Hope this helps :)

  • Like 2
This topic is now closed to further replies.
  • Posts

    • Wow, this is some Iran, Cuba, China, Russia, North Korea-level citizen surveillance right there, the UK's government has gone totally mad. Power trip indeed, their politicians are totally out of control about this issue. They're starting to cross limits I wouldn't have imagined, to be honest. British people, fight this, your privacy and freedoms are in danger. Vote this government out of power.
    • Nintendo unveils The Legend of Zelda: Ocarina of Time remake, and it's out this year by Pulasthi Ariyasinghe Confirming many rumors, Nintendo officially announced a remake of the classic The Legend of Zelda: Ocarina of Time, the very first game in the series that offered a 3D experience to fans. Unlike previous remasters and re-releases, the originally 1998-released fantasy adventure game is being remade from the ground up for the Nintendo Switch 2 console this time. "The Nintendo 64 classic returns for a new generation in 2026, reborn exclusively for Nintendo Switch 2," said the company about today's announcement. While Nintendo didn't go into much detail about the project, other than confirming its existence, we did get a small teaser trailer at the Direct presentation today. Catch the footage below: With a tapestry as the backdrop, the first half of the trailer tells the tale of Hyrule, the Kokiri forest dwellers, and their fairy companions. It goes onto introduce "one particular boy" without a fairy, which then cuts to a sleeping Link, showcasing what looks like the new art style being introduced in the remake. Unfortunately, no gameplay or a look at the world has been revealed yet. The game originally released for the Nintendo 64 back in 1998, offering a time travel adventure where Link is once again going up against the evil king Ganondorf. The hugely well-received title has only been playable on modern Nintendo consoles using the Switch Online + Expansion Pack membership. The Legend of Zelda: Ocarina of Time remake for the Nintendo Switch 2 doesn't have a firm release date yet, but Nintendo says it will be released sometime in 2026. Considering just how many publishers are avoiding the Grand Theft Auto VI release nowadays, the company may copy that strategy and also opt to bring this out before November this year.
  • Recent Achievements

    • Week One Done
      ARaclen earned a badge
      Week One Done
    • One Year In
      jojodbn earned a badge
      One Year In
    • One Month Later
      jojodbn earned a badge
      One Month Later
    • Week One Done
      jojodbn earned a badge
      Week One Done
    • Week One Done
      D0nn13 earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      518
    2. 2
      PsYcHoKiLLa
      229
    3. 3
      +Edouard
      113
    4. 4
      ATLien_0
      87
    5. 5
      Steven P.
      83
  • Tell a friend

    Love Neowin? Tell a friend!