Quote:
Can someone show me how to use recursion in bash script?
|
As in any language... Here's a (not so good) example:
Code:
# find files in directory $1 that are new compared to directory $2
function findNew() {
# $3 is a private parameter for recursion (initial value: .)
local R=${3:-.}
if [ ! -d "${1}/$R" ]; then
return
elif [ ! -e "${2}/$R" ]; then
cd "$1" && find "$R" -type f -depth -print
return
elif [ ! -d "${2}/$R" ]; then
return
fi
for rep in $(cd "${1}/$R" && find . -maxdepth 1 -type d -mindepth 1 -exec basename "{}" \;); do
findNew "$1" "$2" "${R}/$rep"
done
if [ "${1}/$R" -nt "${2}/$R" ]; then
cd "$1" && find "$R" -maxdepth 1 -type f -newer "${2}/$R" -print
fi
}
Quote:
For example, i want to to change the file permission to executable for all the files inside the directory including files in the subdirectory?
|
No need for recursion in this case. Simply do that:
Code:
find "/place/to/work/on" ! -type d -print | xargs chmod a+x
A simple "chmod -R" as suggested is dangerous because in some cases, that is not what you want. In this case it would have worked, but consider the following: you got plenty of mp3 from a CDROM, and all files have the execute bit set; for making those files non-executable, you may try: chmod -R a-x /the/directory; but then even the directories would loose the x bit, and then you could not go inside anymore!
Quote:
BTW, in a bask script, how can we check if the user running this script is super user(root), since only super user can running this script to use the function?
|
The best way to ensure that only root can execute your script is ("#" is root's shell prompt):
Code:
# chown root.root yourscript.sh
# chmod 700 yourscript.sh
("700" can be replaced by: "u=rwx,go=")
Yves.