I want to write an easy script which should include a test: if the command line argument is introduced by the user, then the argument is used; if it’s not, then ignore it. I can’t do it because the stdout of echo is interpreted as stdin for ls. So how can I first test if $1 is typed in by the user without using a second argument $2?
#!/bin/bash
echo "Directory:"
if test -z "$1"
then ls $1
To begin with, your construct is not complete: an if
construct should end in a corresponding fi. - I never use test
(or tthe alias ** ), but the internal bash notation* (a matter of taste). But I would guess that -z means: " if the length of the string equals 0 (zero)". Thus that means that you execute the ls $1* when $1 is empty. This will result in an ls of the working directory. - I do not understand what you mean by " because the stdout of echo is interpreted as stdin for ls.". Explain please.
My solution of this would be:
#!/bin/bash
echo "Directory:"
-n ${1} ]] && ls ${1}
or written longer
#!/bin/bash
echo "Directory:"
if -n ${1} ]]
then ls ${1}
fi
Where you may of course write $1 for* ${1}* (again personal whim).
You are very welcome. I love to work with bash scripts, so please let me know if you have any other questions.
Here are some other interesting values:
$@ or $* = all command line values
$0 = The name of the running script
shift = null <– $1 <– $2 <– $3 … <– $x and so forth where x is the last value entered.
Actually I had one more question related to shift. I wrote a bash script for sending e-mails from command line with mutt, and it looks a bit too complicated:
I use the dashes variable to separate the attachment from the e-mail addresses, that’s a mutt requirement. Do you think I could use “shift” to simplify it a bit? Or, at least, if you could give me an example of how it works.
I am no expert on mutt, but here is an example of using shift. Here is the bash script:
#!/bin/bash
#: Title : testline
#: Date Created: Sun Jan 8 13:54:50 CST 2012
#: Last Edit : Sun Jan 8 13:54:50 CST 2012
#: Author : James D. McDaniel
#: Version : 1.00
#: Description :
#: Options :
while "$1" != "" ] ; do
echo $1
shift
done
exit 0
# End Of Script
I save the script as testline in ~/bin and use the** chmod +x ~/bin/testline** to make it executable. If I run it as follows, here is what I get.
> testline one two three four five
one
two
three
four
five
The terminal command echo $1, never changes, but the shift command keeps moving over the values, until all $values are equal to null. The beauty is the ability to use the same while command, over and over, for all command line values. Again, refer to how I displayed what it does:
shift = null ← $1 ← $2 ← $3 … ← $x and so forth where x is the last value entered.