Bash programming (simple script)


Recommended Posts

Hello everyone,

I'm trying to write simple bash script that will create folder and subfolders with content in it.

User must have two options 1. creating folder structure and 2. deleting that folder structure.

For now I have this:

#!/bin/bash
echo Type 1(creating folder) or 2 (deleting folder)
read choice
if choice=1
then
mkdir itworks_folder
cd itworks_folder
>> itworks.txt
else
echo "Deleting folder structure"
rm -r itworks_folder
fi

The error I get is:

': not a valid identifier

prog.sh: syntax error near unexpected token 'fi'

prog.sh: 'fi'

Keep in mind that this must be simple script as possible.

Link to comment
https://www.neowin.net/forum/topic/843150-bash-programming-simple-script/
Share on other sites

Something simple:

#!/bin/bash

echo "Type 1 (create folder) or Type 2 (delete folder)"
read choice

if [ "$choice" == "1" ];then
  mkdir -pv "itworks_folder" #use "-p" in case directory already exists
  cd itworks_folder
  touch "itworks.txt"
  exit 0 #terminates here
fi

if [ "$choice" == "2" ];then
  echo "Deleting folder structure"
  rm -rv "itworks_folder"
  exit 0 #terminates here
fi

echo "Invalid option"
exit 1

EDIT: ichi beat to it and his is even more simple... :(

just a quick note, I prefer to use

if [ "$choice" == "1" ]; then

instead of

if [ $choice == "1" ]
then

it does not affect the script in any way and does not help your problem (the above solution work), but make it look more "basic like". Also ichi forgot to add " around the variable. It is better to add it because if the variable contain null or a function (don't ask why you would want tot do that), the script will fail. "read" should not return any of these, but it is safer to do that.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.