#!/bin/sh junkdir="$HOME/.junk" do_list=false do_purge=false while getopts 'lp' opt; do case "$opt" in l) do_list=true ;; p) do_purge=true ;; *) printf 'Usage: %s [-l|-p] [ name ... ]\n' "$0" >&2 exit 1 esac done shift "$(( OPTIND - 1 ))" if [ ! -d "$junkdir" ] && ! "$do_purge"; then printf '%s: Missing junk directory "%s"\n' "$0" "$junkdir" >&2 printf '%s: Re-run with -p to create it\n' "$0" >&2 exit 1 fi if "$do_list"; then printf 'Current junk in "%s":\n' "$junkdir" ls -l "$junkdir" fi if "$do_purge"; then printf 'Emptying junk directory "%s"\n' "$junkdir" rm -rf "$junkdir" mkdir "$junkdir" fi if [ "$#" -eq 0 ]; then exit fi echo 'Junking the following things:' printf '%s\n' "$@" mv "$@" "$junkdir"
This script implements what it is you're trying to do. It uses getopts
to parse the command line flags -l
and/or -p
.
I'm setting do_list
and do_purge
in the while loop that parses the command line option because I want to control the order in which the ls
and the rm
takes place further down. If a user uses -lp
or -pl
I want them to see the contents of the junk directory before it is removed.
Removing the junk directory with -p
also recreates it. I do this with rm -rf
followed by mkdir
for simplicity.
After the command line parsing loop, I adjust the positional parameters so that they only contain non-option arguments (names of files and/or directories).
If there are no positional arguments ($#
is zero), I don't try to run mv
to move files to the junk directory.
/bin/s
?$1
should always be quoted:"$1"
. What is[ $HOME/.junk ]
supposed to be/do? And[ $1 = "$@" ]
? Why doeswhile [ $i -le $# ]
start withi=1
instead ofi=0
? What is supposed to happen with a single file argument?mv $s$i
is probably supposed to be an (unquotes, of course) indirection which would have to be done witheval
or (better)"${!i}"
... The counter loop really is the least of your problems.mv "$@" .junk
. Could you explain what your script is doing and why you want the loop?mv "$@" ./junk
will present argument list size problems, but that would take a lot of junk.