Question:
UNIX Bash Shell Scripting Help?
?
2013-04-06 12:31:14 UTC
Having difficulty with the question. I am working in a shell made by my professor.
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
Three answers:
?
2017-01-20 18:30:35 UTC
1
ʄaçade
2013-04-06 13:42:37 UTC
#!/bin/bash



DIR="${1:-$(pwd)}"

cd $DIR

for NAME in *

do

‿ if [[ -f "$NAME" || -d "$NAME" ]] # Skip non-files such as links, pipes, &c.

‿ ‿ then :

‿ ‿ [[ "$NAME" = *.old ]] && continue # Skip names already .old

‿ ‿ echo mv -n "$NAME" "$NAME.old"

‿ fi

done



As always, double/tripple-check my code and see if it works. If so, then remove the "echo" (which is just there for debug purposes).



You do not need the grep in Bash to match file names.
Fred W
2013-04-06 12:45:31 UTC
bash only:



for f in *; do if [ ! $(echo $f | grep "\.old$") ]; then mv $f $f.old; fi; done



using f for filename (less typing)


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...