Home > Enterprise >  How to do a Case statement where it looks for a certain character
How to do a Case statement where it looks for a certain character

Time:10-02

I have to do a case statement in my script where the argument can be written as a DIRECTORYNAME or a PATH/DIRECTORYNAME. So, basically create a directory in the current directory or in the path given by the user. I was thinking of doing something like checking if there is "/" in the argument to know if it is a path or not, but I don't know to code that idea in a case statement. The case statement has to be in that order.

#!/bin/bash

case $1 in #no argument
"") mkdir project
;;
no "/") #don't know how to code it
mkdir $1 
;;
*)#for when argument is path
mkdir $1
;;
esac

Different possibilities of script syntax:

./case.sh
./case.sh DIRECTORYNAME
./case.sh PATH/DIRECTORYNAME

CodePudding user response:

Cases are tested in order, so you need the more specific cases first, and the general case last. So test for / first, and then use * to match everything else. There isn't a way to match "not /" in a case pattern (unless you enable bash extended globbing, which is a nonstandard extension).

case "$1" in
    "") mkdir project ;;
    */*) mkdir "$1" ;;
    *) mkdir "./$1" ;;
esac
  • Related