How are you all. .. I have started to learn bash scripting.. . and I am pretty much trying to execute this script which I am still not successful.. .
This is what I am trying to do. ..
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 with date / count to the new file.
Below is the script I came up with, ,,there may be many mistakes. . . . but . .through mistakes you learn
I think the second error is because there are nothing in $FILENAME because of the first error with basename. This is how to get basename another way: ${1##*/} (if you want it from $1).
I don't understand PATH and FILE in your script, they don't get any values?
I also think you must have a loop in the last part:
should be:
...
else
while [ -r ${SAVEPATH}${FILENAME}.$(date +%Y%m%d).$COUNT ]; do
COUNT=`expr $COUNT + 1`
done
tail -n $2 $1 > ${PATH}${FILENAME}.$(date +%Y%m%d).$COUNT
fi
#!/bin/bash
#USE : ./script_name path_to_file no_of_lines
#Change the SAVEPATH where you need to save
export SAVEPATH="/home/zshaikh/"
export FILENAME=$(basename $1)
COUNT=1
if ! [ -r "$1" ]; then
echo "File does not exist!!"
exit 1
fi
if ! [ "$2" ]; then
echo "Specify no of lines!!!"
fi
if ! [ -e "${SAVEPATH}${FILENAME}" ]; then
tail -n $2 $1 > ${SAVEPATH}${FILENAME}
echo "File saved at ${SAVEPATH}${FILENAME}"
elif ! [ -e "${SAVEPATH}${FILENAME}.$(date +%Y%m%d)" ]; then
tail -n $2 $1 > ${SAVEPATH}${FILENAME}.$(date +%Y%m%d)
echo "File saved at ${SAVEPATH}${FILENAME}.$(date +%Y%m%d)"
else
while [ -e "${SAVEPATH}${FILENAME}.$(date +%Y%m%d).${COUNT}" ]; do
COUNT=`expr $COUNT + 1`
done
tail -n $2 $1 > ${SAVEPATH}${FILENAME}.$(date +%Y%m%d).$COUNT
echo "File saved at ${SAVEPATH}${FILENAME}.$(date +%Y%m%d).$COUNT"
fi