john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

If file or directory exists and case statements string empty

!/bin/bash

the more conservative might choose unix compatible: #!/bin/sh

DIRECTORY="/mnt/external" if [ -d $DIRECTORY ]; then echo "$DIRECTORY exists" else echo "Error, $DIRECTORY does not exist" fi

testing for files is as easy as: if [ -f /etc/passwd ]

http://www.tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html#sect_07_01_02

[ -f /etc/hosts ] && echo "Found" || echo "Not found"

if [ ssh user@host "[ -f /etc/hosts ] && echo 1 || echo 0" == 1 ]; then echo "remote host has directory /some/tests" fi

FileExists=ssh host "test -e /some/testfile && echo 1 || echo 0"

if [ ${FileExists} == 0 ] echo "file does not exist" fi


if [ $condition1 ] && [ $condition2 ] Same as: if [ $condition1 -a $condition2 ]

[ ! EXPR ] returns TRUE if the expression is false

if [ $condition1 ] || [ $condition2 ] Same as: if [ EXPR1 -o EXPR2 ]

== for string comparison -eq = equal integers -ne = not equal -lt = less than -gt = greater than -le = less than or equal to -ge = greater than or equal to -n string (True if str1 is not null, e.g. length is greater than zero) -z string (True if str1 is null, e.g. length is zero) -f = is an ordinary file -d = is a directory -s = is a file AND size is not 0 -r = is readable -w = is writable -x = is executable

-a = AND -o = OR ! = NOT

AWS_INSTALLED=$(/usr/bin/vagrant plugin list | grep vagrant-aws) if [ ! -z "$AWS_INSTALLED" ]; then echo "vagrant-aws already installed: $AWS_INSTALLED" else /usr/bin/vagrant plugin install vagrant-aws fi

http://www.tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html

if [ -z $string -a -le $num -a $compare != 'literal' ]; then rental=" Unknown vehicle " elif [ -n $1 ]; then

otherwise make first arg as rental

rental=$1 fi

case $1 in "eth0") commands here;; "eth1")
"wlan0") echo "here too";; *) echo "default command";; esac

Not a "regular file"

if [ ! -f "/usr/bin/expect" ]; then echo "/usr/bin/expect is not found, please install with apt-get install expect" exit fi


  • « Lxde minimal gui keyring fix wicd
  • Ntp ntpd server client »

Published

Sep 25, 2014

Category

linux

~266 words

Tags

  • and 29
  • case 2
  • directory 13
  • empty 1
  • exists 1
  • file 92
  • if 6
  • or 7
  • scripts 63
  • statements 2
  • string 18