For a loop to find out if a directory exists in unix

I want to use a script that checks if a list of directories exists or not, and at the same time it should print some kind of custom message that I'm sending.

For instance:

I have a script that checks if a directory exists:

**check.sh** for i in $* if [ -d "$i" ]; then echo Found <msg-i> directory. else echo <msg-i> directory not found. 

Now I want to call this script as follows:

 ./check.sh $DIR1 msg1 $Dir2 msg2 $Dir3 msg3 

So, if DIR1 does not exist, I want to display the message as "msg1 directory not found", similarly for DIR2 I want to show "msg2 directory not found". Here msg1 and msg2 are what I want to pass as a string. How to achieve this? I am using a bash shell.

+6
source share
3 answers

Try the following:

 while [ -n "$1" ] do dir="$1" msg="$2" if [ -d "$dir" ]; then echo "$msg dir FOUND" else echo "$msg dir NOT FOUND" fi shift 2 done 
Command

shift <n> just shifts the left positional parameters passed to the script from n positions. For example, if you call a script with:

./myscript 1 2 3 4

$1 is "1" and $2 is "2"

but if you shift 2 , then $1 is "3" and $2 is "4".

Thus, the loop consumes 2 parameters per cycle until parameter $1 is empty ( -n "$1" ).

while can be written more elegantly:

 while (( $# )) 

getting the same result.

You can also check the second parameter ( while [ -n "$2" ] ), but this changes the behavior when the user provides an odd number of parameters:

  • in the first case, the last directory will be checked, but you will have a strange message, because $msg il empty
  • il in the second case, you will not have strange messages, but the last directory will be quietly checked

The best test parameters at the beginning:

 if (( $# % 2 )) then echo "Provide an even number of parameters" exit 1 fi 
+7
source

Chepner says:

The while condition can be simple (( $# )) (if the number of positional parameters is not equal to zero).

Chaitanya says:

Hi Chepner, thanks for providing an alternative solution. Could you tell me what it really should look like in order to use $ #, I tried different ways, but it does not work for me.

Here is an example:

 while (( $# )) do dir=$1 msg=$2 shift 2 [...] done 

while (( $# )) will be true if there are any command line arguments. Running shift twice removes the arguments from the list. When there are no more arguments, the while loop ends.

+4
source

@Zac has the correct answer.

One tip for the post: use printf format printf :

 ./check.sh dir1 "can't locate %s directory" 

and in the script:

 if [[ ! -d "$dir" ]]; then printf "$msg" "$dir" 
0
source

Source: https://habr.com/ru/post/945779/


All Articles