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

    • Mate, you’re looking to spend about $100 - what are you expecting. The A series is not the high end model, no - but “trash” is nonsense. The sort of thing that idiots who only buy the highest end models say as some sort of self validation. They will do everything you need of them.
    • Stack Overflow is launching a version of itself for AI agents by David Uzondu Stack Overflow has announced Stack Overflow for Agents, a platform that traditionally hosts crowdsourced programming solutions for human developers, but now serves autonomous software agents. Basically, Stack Overflow's argument is that the rapid democratization of building software has exposed a major vulnerability. Agents operate in isolation, creating an Ephemeral Intelligence Gap where they waste valuable tokens on something another agent halfway across the world has already solved. That's why, according to the company, a shared, real-time knowledge repository is needed. Stack Overflow for Agents is currently in beta, running as an API-first knowledge exchange where humans review what agents publish. To prevent hallucination issues and keep the database clean, the platform uses a multi-agent verification loop to check code quality. This system forces agents to query the corpus first to locate validated answers rather than running expensive code-generation scripts. To ensure trust, Stack Overflow connects agent contributions directly to the human developer's established reputation through single sign-on credentials. The agents can interact with three distinct post types. One option, Questions, documents unsolved bugs, while "Today I Learned" posts record debugging traces. Blueprints round out the selection by storing reusable design patterns. If an enterprise wants to keep proprietary data private, the Stack Internal platform allows the organization to run the assistant behind its own firewall. Before the massive rise of LLMs, which tanked its traffic by about 50% over the last couple of years, Stack Overflow was the go-to website for millions of programmers seeking coding solutions. Some argue that another reason why the website sort of fell off stems from its notoriously hostile (and condescending) community that frequently closed basic questions and alienated beginners with strict gatekeeping. In order to avoid getting eaten by AI, Stack Overflow has tried several things. When volunteer moderators banned AI-generated content in 2023 to protect data quality, corporate leaders tried to limit those restrictions, prompting the volunteers to stage a massive site-wide strike. Since then, the developer portal has signed major deals with tech companies like Google to bring Stack Overflow data directly into Gemini models and Google Cloud console. A similar deal with OpenAI in 2024 sparked an uproar, leading some users to delete old answers in protest. The company swiftly suspended those accounts to protect the database. It has also experimented with OverflowAI, an AI-powered conversational search tool designed to pull together answers from multiple threads.
    • There are two options for smartphone platforms so consumers don't have much of a choice there. The EU is not making any decisions for customers they just want them to have options if they so choose. I am not sure why you would be for closed platforms. The big tech companies already have so much power and money while are relatively unregulated in the US which is why they run into so much trouble in the EU.
    • Hello, I am using a Moto G Stylus (2025) and happy with it.  I don't know how well the model works on Twigby's network (it looks like they are an MVNO of Verizon).  It looks like they have a BYOD plan, though, so as long as you find a device that works on their network you should be okay.   Regards,   Aryeh Goretsky 
  • Recent Achievements

    • First Post
      StaticMatrix earned a badge
      First Post
    • Week One Done
      StaticMatrix earned a badge
      Week One Done
    • Rookie
      lamborghiniv10 went up a rank
      Rookie
    • One Month Later
      pinnclepd earned a badge
      One Month Later
    • First Post
      X-No-file earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      533
    2. 2
      PsYcHoKiLLa
      209
    3. 3
      +Edouard
      151
    4. 4
      Steven P.
      100
    5. 5
      ATLien_0
      84
  • Tell a friend

    Love Neowin? Tell a friend!