flags vs normal arguments
I'm writing a bash script that takes optional user input, a pathname. If it is not specified "pwd" will be used. But what is the best way to do this?
Code:
$command path Code:
$command -d path |
If a path is necessary but simply has a default, it is best not for it to be an option e.g. find command.
|
You might consider using the bash built-in "getopts". It works like the C language function of the same name. If an option requires an argument, a semicolon will follow the option letter in the option string. Then you can simply read the $OPTARG variable for the value of the argument. Typing in "help getopts" in the bash shell will give you some information. Also detailed information should be in the bashref manual.
Your question reminds me of the optional destination directory option of the "mv" command, i.e. the '-t' option, which allows its use with the "xargs" command. |
Yes, I already looked at 'getopts'. But it only takes care of arguments with a trailing '-' (flags), I thought?
|
If you have regular arguments, rather than option arguments, you can use the value of $OPTIND to determine where to start regular processing. If you will only have one optional command argument, then you don't need to use options. Instead check for the existence of an argument, if one doesn't exist, i.e. $# is 0, then use $PWD; otherwise if $# is 1, use the supplied argument.
|
This is what I've done:
Code:
#! /bin/bash |
if you want to use flags and arguments all you have to do if find out how many arguments were sent into the script and use a case block to execute what you want
Code:
case "$number_of_args" in peace out, later |
The code you posted works. If the path must exist ahead of time, consider using the "-d" test:
if [ -d "$1" ]; then This will test whether the path name in the arguments exists, and whether it is a directory. |
All times are GMT -5. The time now is 03:34 PM. |