Shell Script - Make directory if it doesn't exist -
i want enter name of directory , check if exists. if doesn't exist want create error mkdir: cannot create directory'./' file exists
my code says file exists though doesn't. doing wrong?
echo "enter directory name" read dirname if [[ ! -d "$dirname" ]] if [ -l $dirname] echo "file doesn't exist. creating now" mkdir ./$dirname echo "file created" else echo "file exists" fi fi
if [ -l $dirname]
look @ error message produced line: “[: missing `]'” or such (depending on shell you're using). need space inside brackets. need double quotes around variable expansion unless use double brackets; can either learn rules, or use simple rule: always use double quotes around variable substitution , command substitution — "$foo"
, "$(foo)"
.
if [ -l "$dirname" ]
then there's logic error: you're creating directory if there symbolic link not point directory. presumably meant have negation in there.
don't forget directory might created while script running, it's possible check show directory doesn't exist directory exist when try create it. never “check do”, “do , catch failure”.
the right way create directory if doesn't exist is
mkdir -p -- "$dirname"
(the double quotes in case $dirname
contains whitespace or globbing characters, --
in case starts -
.)
Comments
Post a Comment