I was just wondering whether or not this script code would properly test for the existence of a dir2, and if it doesn't exist, then to create it. Dir1 already exists.
[ ! -d /dir1/dir2 ] && mkdir /dir1/dir2
Your command can fail if dir1/dir2 exists but is not a directory. If you want to test whether dir1/dir2 exists at all, use -e
[ -e dir1/dir2 ] || mkdir dir1/dir2
If you really need dir1/dir2 to be a directory, and an ordinary file with that name is an error and should be replaced, you can test for that case.
[ -e dir1/dir2 ] && [ ! -d dir1/dir2 ] && rm dir1/dir2
[ -d dir1/dir2 ] || mkdir dir1/dir2
dir1 exists, because you know it does.
/dir1/definitely already exists. Usemkdir -p /dir1/dir2and forget thetest.mkdir -pwill fail as well ifdir2exists as a file other than a directory - or if permissions forbid you to create dirs for whatever reason. I usually do likemkdir -p ./target/dir && cd ./target/dir || exit