M HYPE SPLASH
// updates

How do I use command line arguments in bash?

By Sarah Scott

This script moves all the doc files to a specified directory. I have managed to put an argument but the problem I am facing is putting the full path where the scripts are moving to, for example I want to run the script like this below

./loo -d then path where im moving the files (i.e ./loo -d the second argument where files are moving to)

this is my code

#!/bin/bash
From="/home/elg19/lone/doc"
To="/home/elg19/documents"
if [ $1 = -d ]; then
cd "$From"
for i in pdf txt doc; do find . -type f -name "*.${i}" -exec mv "{}" "$To" \;
done
fi
0

3 Answers

You need getopts. getopts is a library designed to handle commandline arguments for you, and is generally available in many languages. In bash, you use it like this:

This is borrowed from a tutorial I found:

From="/home/elg19/lone/doc"
To="/home/elg19/documents"
while getopts "d:" optionName; do case "$optionName" in d) To="$OPTARG";; [?]) exit 255;; esac
done
[[ -d "$To" ]] || exit 255
cd "$From"
for i in pdf txt doc; do find . -type f -name "*.${i}" -exec mv "{}" "$To" \;
done

This is untested, but basically it's just your script with the option to override the "$To" argument with getopts.

The [?] bit tells it to exit if any unrecognised options are found.

12

FWIW, rsync will do this for you

rsync --filter="+ *.doc" --filter="+ *.pdf" --filter="+ *.txt" --filter="- *" ~lone/doc/* ~/documents/

You can make an alias in .bashrc if you wish

alias backup='rsync --filter="+ *.doc" --filter="+ *.pdf" --filter="+ *.txt" --filter="- *" ~lone/doc/* ~/documents/'

If you need more then *.doc, add to the --filer="+ *.txt" ;)

See my comment if you want to debug your script. Your problem in your script may be as simple as your conditional if [ $1 = -d ]

try

if [ -d "$1" ]; then

But I can not tell from your script what options you are passing and why (you defined your directories in your script).

3

With your most recent comment

#!/bin/bash
From="/home/elg19/lone/doc"
#To="/home/elg19/documents"
while getopts "d:" optionName; do case "$optionName" in d) To="$OPTARG";; [?]) exit 255;; esac
done
[[ -d "$To" ]] || exit 255
for i in pdf txt doc; do find $From -type f -name "*.${i}" -exec mv "{}" "$To" \;
done
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy