sans sans - 7 months ago 13
Bash Question

shell script that takes a file name as an argument and deletes this file from every directory above the pwd in Unix / Linux / Ubuntu

my shell script is as follows.

if [ $# -eq 0 ]
then
echo "pass the file name"
exit
fi
fl=$1
ch=1
h=/home

while [ $ch -eq 1 ]
do
cd ..
p=`pwd`
echo "$p/$fl"
rm `echo "$p/$fl"` 2> /dev/nullif [ $p = $h ]
then
ch=0
fi
done


but when executing shows a syntax error.
line16: syntax error near unexpected token
then'
line 16:
then'

What is the mistake in this script?

Answer

You misplaced if the script.

if [ $# -eq 0 ]
then
    echo "pass the file name"
    exit
fi

fl=$1
ch=1
h=/home

while [ $ch -eq 1 ]
do
    cd ..
    p=`pwd`
    echo "$p/$fl"
    rm `echo "$p/$fl"` 2> /dev/null
    if [ $p = $h ]
    then
            ch=0
    fi
done