PDA

View Full Version : If statements in shell




lynkynpark86
Apr 11, 2012, 09:25 AM
Does anyone know how I would do this in a shell script?
If x is a file: somecommand
If x is a directory: someothercommand



throAU
Apr 11, 2012, 09:43 AM
Which shell? sh? csh?

edit:

you could use "test".

read

man test

dmi
Apr 11, 2012, 10:03 AM
test -f x && somecommand
test -d x && someothercommand

subsonix
Apr 11, 2012, 10:37 AM
[ is an alias for test, which is quite funny I think. :D Try: man [ it will bring up the manual for test. It gives a bit more syntactically pleasing look if used in a script.


if [ -f $1 ]
then
echo file
else if [ -d $1 ]
echo directory
fi

seepel
Apr 11, 2012, 10:19 PM
[ is an alias for test, which is quite funny I think. :D Try: man [ it will bring up the manual for test. It gives a bit more syntactically pleasing look if used in a script.


if [ -f $1 ]
then
echo file
else if [ -d $1 ]
echo directory
fi


this hits the nail on the head and for more detail see http://tldp.org/LDP/abs/html/fto.html

chown33
Apr 12, 2012, 12:24 AM
this hits the nail on the head and for more detail see http://tldp.org/LDP/abs/html/fto.html
Aha, it's: The Linux Documentation Project. Not: Too Long Didn't P*.

FWIW, there are also the shell builtins [[ and ]], via 'man bash (https://developer.apple.com/library/mac/#documentation/Darwin/Reference/Manpages/man1/bash.1.html)'. Somewhat different syntax for the expressions, but otherwise the same as test and [ (which are also bash builtins).

dmi
Apr 12, 2012, 04:42 PM
test and [ are /bin utilities, which would work in all shells
[[ ... ]] is a bash (and ksh) built in

chown33
Apr 12, 2012, 08:43 PM
test and [ are /bin utilities, which would work in all shells
[[ ... ]] is a bash (and ksh) built in

FWIW, test and [ are bash builtins. They also exist as /bin tools, but bash (like other shells) searches its builtins first, unless the command contains a slash.

Try this:
type [ test

type is another builtin, otherwise similar to which (which isn't a builtin in bash).