On 16Aug2014 14:44, Mike Wright <mike.wright@xxxxxxxxxxxxxx> wrote:
I'm trying to write a simple script that if provided an argument, uses that, or if nothing is provided, uses a predefined string.
This is general shell stuff, not bash specific.
if [ -n $# ]
This is always true. Even "0" is a nonempty string.
Test [ $# -gt 0 ] instead.
WORDS=$1
else
WORDS="these are some words"
fi
I write this stuff like this:
# very near the top of the script
words="these are some words"
[... command line parsing...]
if [ $# -gt 0 ]
then
words=$1
shift
fi
Tip: run your script with "-x":
sh -x my_script
It will show the actual commands executed.
Finally:
Never use $UPPERCASE names for variables that are local to your script. Use
lower case for script-local variables.
Why?
- exported variables are by convention names with upper case, so using lower
case makes it obvious that this variable is for your script versus general use
(like $PATH)
- if a variable _is_ in the exported environment, and your script uses that
name, the changed value will get exported to all the commands your script runs
even if you don't export it yourself: it came in from the extrernal environment
and it will automatically go out with the environment given to subcommands
- you can't expected (or be expected) to know every exported name that can
possibly be used, nor even those commonly in use; by adopting the use of lower
case names for script-local variable you entirely avoid needing omniscience
about exported names.
You're writing the script with $WORDS probably because there are many many
example scripts like it. They've been written by people who have never thought
this through.
Cheers,
Cameron Simpson <cs@xxxxxxxxxx>
Fatal error! Hit any user to continue...
- Phillip Coles <Phillip.Coles@xxxxxxxxxxxxxxxx>
--
users mailing list
users@xxxxxxxxxxxxxxxxxxxxxxx
To unsubscribe or change subscription options:
https://admin.fedoraproject.org/mailman/listinfo/users
Fedora Code of Conduct: http://fedoraproject.org/code-of-conduct
Guidelines: http://fedoraproject.org/wiki/Mailing_list_guidelines
Have a question? Ask away: http://ask.fedoraproject.org