An script that accepts a command
#!/bin/sh
#My script
echo "Are you sure you want to reorganize your files?"
echo "Type y or Y to continue. Anything else will stop the process"
read response
if [ "$response" = "y" ] || [ "$response" = "Y" ]; then
mkdir video
mkdir 开发者_开发技巧audio
mkdir text
mv -v *.txt text >> log.txt
mv -v *.wmv video >> log.txt
mv -v *.mov video >> log.txt
mv -v *.mpg video >> log.txt
mv -v *.mp3 audio >> log.txt
mv -v *.wma audio >> log.txt
echo "Yay, it worked!"
else
echo "Nothing happened."
fi
I wrote the script above to organize files into subfolders. For instance the music files will go into an audio folder. Now I would like to take a step further and make it more global.I would like to allow the script to accept a command line argument, which is the folder that contains the unorganized files. This should allow the script to be located and run from anywhere in the file system, and accept any folder of unorganized files.
Example:
organizefiles.sh mystuff/media // subfolders would go inside "media"
the folder media contains all of the media files.
Thank you!
A portion of your script could use the first positional parameter like this:
if [ -d $1 ]
then
mkdir video
mkdir audio
mkdir text
mv -v $1/*.txt text >> log.txt
mv -v $1/*.wmv video >> log.txt
mv -v $1/*.mov video >> log.txt
mv -v $1/*.mpg video >> log.txt
mv -v $1/*.mp3 audio >> log.txt
mv -v $1/*.wma audio >> log.txt
else
echo "The destination directory does not exist"
exit 1
fi
You can refer to the command line parameters as $1, $2, etc. The first one is $1. Here's a good description of how to pass arguments to a script: http://docsrv.sco.com:507/en/OSUserG/_Passing_to_shell_script.html
Scripts has access to arguments on the command line via some variables like this:
$1, $2, ..., $n - refers to first, second up to n arguments.
Example: Typing myscript.sh foo will set foo to the $1 variable.
Bash arguments are fairly straightforward, using a $#
format. So for example, you could access the first argument of the command line from your script with $1
In your script, you could do something like so:
if [ -z $1 ]
then
dir = $1
else
dir = './'
fi
Then just add the new $dir
variable to the paths in your mv
commands. I recommend checking out Bash By Example from IBM. A great article series to teach you Bash.
Note that there may be a petter better to do what I suggested but I am nowhere near an expert in Bash. :-)
here's a simple system. you can use case/esac instead of if/else for neatness. also, rearranged the mv commands a bit
#!/bin/bash
dir=$1
cd $dir
while true
do
echo "Are you sure you want to reorganize your files?"
printf "Type y or Y to continue. Anything else will stop the process: "
read response
case "$response" in
y|Y )
mv -v *.txt text >> log.txt
for vid in "*.mov" "*.wmv" "*.mpg" "*.wma"
do
mv $vid video >> log.txt
done
echo "yay"
break;;
*) echo "Invalid choice";;
esac
done
精彩评论