Register
It is currently Wed Sep 17, 2014 5:32 am

Conditional statement - create directory


All times are UTC - 6 hours


Post new topic Reply to topic  [ 3 posts ] 
Author Message
 PostPosted: Sat Nov 09, 2013 7:15 am   

Joined: Sat Nov 09, 2013 6:23 am
Posts: 1
Code:
#!/bin/bash
#
echo Utworzyć nowy katalog {TAK/NIE}?
read ZMIENNA
if [ $ZMIENNA -eq TAK] then
    echo "Podaj nazwę katalogu."
    read KATALOG
    mkdir $KATALOG
elif [ $ZMIENNA -eq NIE ] echo "koniec"
    fi

I would like the script ask to create a new directory, after that ask for a name and create it. Now the program returns an error: ./skrypt123: line 14: syntax error at unexpected token `elif '


Top
 Profile  
 PostPosted: Sat Nov 09, 2013 1:57 pm   
User avatar

Joined: Wed Jun 08, 2011 8:27 am
Posts: 189
Location: outer Shpongolia
The error comes from the fact that [(0)'s last argument must be « ] ».
Here, its last argument is « TAK] ».

if keyword must be followed by then on a newline, as does elif.
If you want then to be on the same line as the if or elif, put a semicolon before it.

-eq is used to test integers; you want = here.

Also, in bash(1) it's preferred to use the keyword [[ instead.

I would write it like this:
Code:
#!/bin/bash

read -rp 'Utworzyć nowy katalog {TAK/NIE}? ' zmienna

if [[ $zmienna != TAK ]]; then
    echo 'koniec...'
    exit
fi

read -rp 'Podaj nazwę katalogu : ' katalog

if [[ ! -d $katalog ]]; then
    mkdir "$katalog" || exit 1
fi


Top
 Profile  
 PostPosted: Sun Nov 10, 2013 8:38 pm   
User avatar

Joined: Fri Jul 22, 2011 5:39 pm
Posts: 47
You also may wish to add some basic checking to see if directory exists.
Something like
Code:
...
read KATALOG
if [[ -d "$KATALOG" ]] ; then
  echo "Already exits
else
  mkdir $KATALOG
fi


Top
 Profile WWW  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 3 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 3 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
cron


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP