?
2013-04-06 12:31:14 UTC
If the script is correct, I can go to the next question, but I am stuck. I know there can be many ways of doing this but I cannot find the correct aswer. I met with my tutor and he coudlnt figure it out. He mentioned, I need to use parameters
Question:
You will write a bash shell script called 'oldfiles' which takes one argument, the name
of a directory, and adds the extension ".old" to all visible files in the directory that
don't already have it. Treat subdirectories the same as ordinary files. For example:
$ ls
file1 file2.old file3old file4.old
$ oldfiles .
$ ls
file1.old file2.old file3old.old file4.old
Within 'oldfiles', use a "for" control structure to loop through all the non-hidden filenames
in the directory name in $1. Use a meaningful loop variable, for example "filename" would make sense. Also, use command substitution with "ls $1" instead of an ambiguous filename, or you'll descend into subdirectories.
Next, within the loop, continue to use an "echo" to display the value of the "filename"
variable, and pipe the output into a "grep". The grep should search for the ".old" extension.
A regular expression such as "\.old$" would be the easiest way to do this.
Within the loop, check the exit status of the "grep" with an "if" control structure. If the
"grep" is unsuccessful in finding ".old", then the file should be renamed.
The renaming can be done with a simple "mv" command, renaming "$1/$filename" to
"$1/$filename.old".
Once this works, don't forget to redirect the "grep" output to "/dev/null".
--------------------------------------…
My answer1 :
#!/bin/bash
for filename in $(ls * | grep -v '\.old$' 2> /dev/null)
do
#echo $filename | grep -v '\.old$' 2> /dev/null)
mv "${filename}" "${filename}.old"
done
--------------------------------------…
Answer2:
#!/bin/bash
for filename in $(ls $1)
do
if [ ! grep '\.old$' ]
then mv $1/$filename $1/$filename.old
fi
done
If anyone can help, thanks in advance