-1

I am new to bash and I need to write an if statement within my code however I am unsure how to write is so that if $someVar is found then run this else do that. In this case $someVar is a file and I am not wanting to output text just run another line of code in this case creating the file.

Code:

rm /var/path/to/folder/$someVar

for i in `seq 3 253`

do

echo $ALLOCATION.$i >> /var/path/to/folder/$someVar
5
  • Short answer if [[ -n $someVar ]]; then .. do your stuff .. fi Any bash reference will explain and man bash will also explain the type of conditional expressions (or tests) available. Commented Nov 24, 2015 at 5:35
  • @Joe Have updated question Commented Nov 24, 2015 at 5:35
  • @DavidC.Rankin Thanks, I also have updated my question Commented Nov 24, 2015 at 5:36
  • One other question -- when you say exists do you mean the file with the same name as the variable contents exists, or do you just mean that $someVar is set and is not empty? To test if a file with the name held by $someVar exists, it is if [[ -f $someVar ]]; then ... do your stuff ..fi. You can also just use a compound command to check and conditionally remove the file [[ -f $someVar ]] && rm /var/path/to/folder/$someVar Commented Nov 24, 2015 at 5:37
  • @DavidC.Rankin The latter are you able to put it as an answer so I can make sure I have the correct formatting? Commented Nov 24, 2015 at 5:41

1 Answer 1

1

To check for the existence of /var/path/to/folder/"$someVar", then you can use:

#!/bin/bash

if [[ -f /var/path/to/folder/$someVar ]]; then

    rm /var/path/to/folder/"$someVar"

fi

for i in `seq 3 253`; do

        echo $ALLOCATION.$i >> /var/path/to/folder/"$someVar"

done

You can also use a simple compound-command:

#!/bin/bash

[[ -f /var/path/to/folder/$someVar ]] && rm /var/path/to/folder/"$someVar"

for i in `seq 3 253`; do

    echo $ALLOCATION.$i >> /var/path/to/folder/"$someVar"

done

Note: within [[ ... ]] you do not have to quote your variable to protect against spaces in the variable. In all other cases you should (as a rule of thumb).

Also, note to check whether the file is writeable (i.e. you have permission to remove it), you can use [[ -w /var/path/to/folder/$someVar ]]

Not the answer you're looking for? Browse other questions tagged or ask your own question.