Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
I'm new to bash scripting and for practice I'm making a script called rubbish as an alternative for "rm". The idea is if you type "rubbish file1 file2" it sends unwanted files to a directory called rubbish. "rubbish -l" lists files in rubbish. "rubbish -r" deletes them.
The problem is that the two groups of commands (see script below) work when they're in separate scripts. But when they're together, I get error messages like this:
> trash -l
> rubbish -l mv: invalid option -- l
> Try `mv --help' for more information.
> ashley pig cow janeIt lists the contents of the rubbish directory but also picks up the "mv" command. How can I fix this problem? Any pointers on fixing my script would be much appreciated! Thanks :D
============================================
#!/bin/bash
rubbish(){#works in a separate script
while getopts lr opt
do
case $opt in
l) ls ~/.rubbish
;;
r) rm ~/.rubbish/*
echo ".rubbish directory emptied."
;;
*) echo "Use -l or -r only."
;;
esac
done#works in a separate script
filename=$*
mv filename ~/.rubbish
}

I assume that the 'mv' line is actually:
mv $filename ~/.rubbish
In that case, the problem is that if you say something like:rubbish -l
the 'mv' line will look like:
mv -land 'mv' doesn't know what to do with -l
There are multiple approaches to fix this.
1 - it seems to me that you would want to run the 'mv' only if no arguments are given, meaning the 'mv' wouldn't execute if a -l or -r argument was given. Unless getopts has a way to tell you that there were no - arguments, the way to do this might be to set a flag to true if you process a -l or -r and then after the loop, check the flag. If it is false, then do the 'mv'.
2 - if you really do want to run the 'mv' after a -l or -r argument, then you need to use the 'shift' command to remove the -l from the argument list. I think that putting 'shift 1' inside the -l and -r case options will do that for you. I haven't tested this or looked at the man page for shift.

Thanks for the tip, Don. I haven't looked at setting flags or using shift yet, hopefully I'll work it out after reading about them.

![]() |
kde hangs after modem dis...
|
Redhat 8.0 installation t...
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |