I have a simple script that checks if a file has write permission on it or No. If yes, then it allows the user to append some text data to end of file. If No, it kicks user back out.
I am following a youtube series for learning Shell scripting by ProgrammingKnowledge. Specifically Video 7.
Here is the script:
echo -e "Enter file name: \c" read filename if [ -f $filename ] then if [ -w $filename ] then echo "Type some text data. To quit, press CTRL + d: " cat >> $filename else echo "File has no write permissions" fi else echo "$filename is not found" fi
My script allows still allows the user to append to the file provided, even if it has no write permission. Other flags like
-s are working as expected. What is wrong here?
ls -l on available files:
-r--r--r-- 1 nobody nobody 0 Dec 6 12:25 Mane -r-xr-xr-x 1 root root 165 Dec 6 12:06 Ramy.txt -r--r--r-- 1 root root 0 Dec 6 12:24 Salah
The output of running the script with Debug turned on:
[root@Console2-4KMH2 scripts]# bash -x ./hello_FILE_TEST_OPERAT_APPEND_2_File.sh + echo -e 'Enter file name: \c' Enter file name: + read filename Salah + '[' -f Salah ']' + '[' -w Salah ']' + echo 'Type some text data. To quit, press CTRL + d: ' Type some text data. To quit, press CTRL + d: + cat
My question got resolved. Thanks everyone for all the edits on my rookie post. Stephen Harris in the comments section spotted that I am running the script as a root user, and highlighted that root will write to a file even if said file has no write permissions on it. I created a sudo user, re-ran the script and found it to behave as expected (not writing to file that have no write permissions)